【问题标题】:Create new "Item" and all associated properties创建新的“项目”和所有相关属性
【发布时间】:2019-06-27 14:47:29
【问题描述】:

我有一个产品表和一个配方表,其中一个外键使用产品表->ID 链接表,我想知道我是否可以同时创建产品和添加配方,或者唯一的方法是创建产品,然后在不同的视图中添加食谱。

我在网上寻找过类似的情况,但没有成功。

【问题讨论】:

  • 你不能放一些代码吗?
  • 说实话,没有代码,因为我一直在摸索如何从产品表中捕获 ID 并将其用作外键在配方中。我只是想知道它是否可能,如果可能,它背后的理论是什么,给我一个坚实的基础来开始编码。谢谢
  • if I can create the Product and add the recipe at the same time => 如果这是从 UI 的角度来看,那么当然可以。如果这是从数据库的角度来看,那么总是先父后子。因此,将首先插入产品表,然后使用产品的主键进行收据。
  • 从用户的角度来看它将是无缝的,但从数据库的角度来看,我会做 2 次插入吗? 1 - 将新项目插入产品。 2- 获取 lastinsertid()。 3. 使用 lastinsertid()? 插入食谱。听起来对吗?
  • 您应该彻底阅读How to Ask 和@Dave 提供给您的其他几个链接。这个问题太笼统了,没有具体的问题,还有例子(包括minimal reproducible example,在这种情况下适用)和细节。

标签: php mysql laravel


【解决方案1】:

如果您在模型中定义了关系。

您可以使用attach方法添加数据相关表。

$recipe = $request->get('recipe');
$product =   $request->get('product')        
$product = New Product();
$product = $product->create($product);
if($product){
    $product->recipe()->attach($recipe); 
}

【讨论】:

    【解决方案2】:

    谢谢大家想通了.. 先保存配方,然后从保存的配方中获取最后一个 ID 然后用百分比保存关联的材质。

      $recipe = new Recipe([
            'name' =>$request->get('name'),
            'description' => $request ->get('description')
        ]);
        $recipe ->save(); // Save the above and get the ID
    
        $recipematerial= new RecipeMaterial([
            'material_id' => $request ->get('material'),
            'recipe_id' => $recipe->id,
            'percentage' => $request ->get('percentage')
        ]);
        $recipematerial ->save(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多