0

我有 3 个相关模型,我正在尝试为其构建 CRUD 接口:

  1. 酒馆
  2. 菜单
    • 属于酒吧
    • 有很多菜
  3. 盘子

当我提交表单以保存所有结果时,我不确定如何删除所有不再需要的菜单和菜肴(即,它们未提交保存)。我知道 Laravel 有几个选择:

这是我的控制器看起来有点像这样:

public function save()
{
    // This is actually loaded from the database, not created.
    $pub = Pub::create();

    // I load the models from the database and convert them to an array for usage in Livewire
    // Perhaps keeping them as models would make this easier?
    $menus = [
        // This Menu came from the database as it has an ID
        // so the database row needs updating
        [
            'id' => 1,
            'name' => 'Example Menu'
        ],

        // This menu is newly submitted as it has no ID
        // the database row needs creating and associating with the Pub model
        [
            'name' => 'Example Menu 2'
        ]
    ];

    // I load the models from the database and convert them to an array for usage in Livewire
    // Perhaps keeping them as models would make this easier?
    $dishes = [
        // This Dish came from the database as it has an ID
        // so the database row needs updating
        [
            'id' => 1,
            'name' => 'Example Dish',
            'price' => 10
        ],

        // This menu is newly submitted as it has no ID
        // the database row needs creating and associating with the Pub model
        [
            'name' => 'Example Dish 2',
            'price' => 5
        ]
    ];

    // I can't do this as deleting from the database means they will lose their
    // associated media via the Laravel Media Library
    $pub->menus()->delete();
    $pub->menus()->saveMany($menus);
    
    // Which leaves me with something similar to this, but it quickly gets "messy":
    
    // Attempt to find what menus are no longer wanted and delete only them
    $pub->menus()->whereIn('id', $unwantedMenuIds)->delete();
    
    // Now go through all menus and only delete the dishes that are no longer wanted
    foreach($menus as $menu) {
        $menu->dishes()->whereIn('id', $unwantedDishIds)->delete();
    }
    
    // Now either update or create all menus and their associated dishes
    // Followed by associating any new media to the relevant models
 }

找出需要删除的模型,尤其是对于嵌套关系,很快就会变得一团糟。我已将其排除在上述代码片段之外。

4

0 回答 0