简体   繁体   中英

How to find and merge two rows into one

I am new to Laravel so I am confused how to do this

I have a table called groups where I forget to use unique in validation. After Long time I found out there are multiple datas with same name for ex: I have two datas with same name called Feminism but with different id The group table have only name and description columns, but it has relation with products many to many I have other datas too which has same name I want to merge those datas into one. along with the relation to the product. Is is possible?

Shall I have to check all the names manually like

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

and then merge those datas or we have some other relavant methods

You can refactor this code for your models and relations

    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"
            ]);
        }
    }

You may use the following

$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();

Use onDelete cascade when defining your pivot table migration. This takes care of deleting the model's relations for you: eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM