【问题标题】:How to find and merge two rows into one如何查找并将两行合并为一
【发布时间】:2020-04-28 07:44:29
【问题描述】:
我是 Laravel 的新手,所以我很困惑如何做到这一点
我有一个名为 groups 的表,我忘记在验证中使用 unique 。很长一段时间后,我发现 ex 有多个具有相同名称的数据:
我有两个名称相同但 ID 不同的数据
组表只有name 和description 列,但它与产品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’);