代码之家  ›  专栏  ›  技术社区  ›  Mikey

在Laravel中使用雄辩更新一对多关系

  •  0
  • Mikey  · 技术社区  · 8 年前

    我对拉勒维尔比较陌生。我正试图找出如何使用具有雄辩的ORM的事务,特别是在关系方面。

    假设两个表之间有一对多关系: Recipes Ingredients ,分别是。

    [
        'id' => 1,
        'name' => 'Lasagna',
        'readyIn' => '30 minutes',
        'ingredients' => [
            ['id' => 1, 'name' => 'noodles', 'quantity' => '8'],
            ['id' => 2, 'name' => 'cheese', 'quantity' => '2 cups']
        ]
    ]
    

    更新现有配方时,我的请求是:

    [
        'id' => 1,
        'name' => 'Lasagna',
        'readyIn' => '1 hour',
        'ingredients' => [
            ['id' => 1, 'name' => 'noodles', 'quantity' => '9'],
            ['id' => 2, 'name' => 'mozarella cheese', 'quantity' => '3 cups'],
            ['id' => null, 'name' => 'sauce', 'quantity' => '1 jar'],
            ['id' => null, 'name' => 'onion', 'quantity' => '1']
        ]
    ]
    

    我的方法是执行以下操作来更新配方:

    DB::transaction(function() use ($request, $id) {
        // update existing recipe
        $recipe = Recipe::find($id);
        $recipe->fill($request->all());
        $recipe->save();
    
        // get old & new ingredients
        $oldIngredients = $recipe->ingredients();
        $newIngredients = $request->get('ingredients');
    
        // delete old ingredients that do not appear in the new list
        if ($ids = array_diff(
            array_pluck($oldIngredients, 'id'),
            array_pluck($newIngredients, 'id')
        )) {
            Ingredient::destroy($ids);
        }
    
        // save new ingredients
        foreach ($newIngredients as $attributes) {
            // update existing ingredient
            if ($id = array_pull($attributes, 'id')) {
                $ingredient = Ingredient::find($id);
                $ingredient->fill($attributes);
                $ingredient->save(); 
            // create new ingredient
            } else {
                $recipe->ingredients()->create($attributes);
            }
        }
    });
    

    成分 $recipe 的配料?就像在 Ingredient::destroy($ids) $ingredient->save() 成分 $配方 $配方 当我更新或删除配料时?我的目标是更新 $配方

    0 回复  |  直到 8 年前