【问题标题】:How to find and merge two rows into one如何查找并将两行合并为一
【发布时间】:2020-04-28 07:44:29
【问题描述】:

我是 Laravel 的新手,所以我很困惑如何做到这一点

我有一个名为 groups 的表,我忘记在验证中使用 unique 。很长一段时间后,我发现 ex 有多个具有相同名称的数据: 我有两个名称相同但 ID 不同的数据 组表只有namedescription 列,但它与产品many to many 有关系我也有其他具有相同名称的数据我想将这些数据合并为一个。以及与产品的关系。有可能吗?

我必须像手动检查所有名称吗

Item::where('name','Feminism')->get();

然后合并这些数据或者我们有一些其他相关的方法

【问题讨论】:

  • 你能把你的数据库模式结构也加入你的模型吗?

标签: php mysql laravel eloquent


【解决方案1】:

您可以为您的模型和关系重构此代码

    foreach ($groups as $group) {
        $duplicates = Group::where('name', $group->name)->where('id', '<>', $group->id)->get();
        foreach ($duplicates as $duplicate) {
            $mustBeUpdatedRelation = $duplicate->products;
            $anotherRelation = $duplicate->anotherRelation;
            foreach ($mustBeUpdatedRelation as $product) {
                $product->categories()->detach($duplicate->id); // if product has pivot data you must get these and assign to new relation

                //new relation
                $product->categories()->attach($group->id);
            }

            $anotherRelation = $duplicate->anotherRelation;
            foreach ($anotherRelation as $item) {
                // like above
                // detach duplicated
                // attach unique
            }

            //finally you can delete or .... duplicated group
            $duplicate->update([
                'name' => "duplicated_$duplicate->name"
            ]);
        }
    }

【讨论】:

    【解决方案2】:

    你可以使用以下

    $items = App\Item::with('products')->get();
    
    $tempArr = [];
    foreach ($items as $key => $item) {
        if(isset($tempArr[$item->name])) {
    
            $merged = $tempArr[$item->name]['products']->merge($item->products);
    
            unset($tempArr[$item->name]['products']);
            $tempArr[$item->name]['products'] = $merged;
    
        } else {
    
            $tempArr[$item->name] = $item;
        }
    }
    
    
    foreach ($tempArr as $item) {
        $item->products()->sync($item->products->pluck('id')); 
    }
    
    $idsToKeep = array_column($tempArr, 'id');
    
    App\Item::whereNotIn('id', $idsToKeep )->delete();
    

    在定义数据透视表迁移时使用onDelete 级联。 这会为您删除模型的关系: 例如

    $table->foreign(’item_id’)
          ->references(’id’)->on(’items’)
          ->onDelete(’cascade’);
    

    【讨论】:

    • 好的,这里的产品是指我的代码中的组对吗??
    • 您能添加您的数据库架构以便我帮忙吗?
    猜你喜欢
    • 2017-08-17
    • 2022-12-18
    • 1970-01-01
    • 2015-02-08
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多