我有一个有3列id, sub_id, name
的表。那是一张相当大的桌子,还有一些复制件。
什么是最好的方法来检测副本,以便我可以删除他们?
我尝试过这样做,但是它返回了所有的东西(我想it使它们变得非唯一)
$collection = \App\MyModel::all();
$colUnique = $collection->unique(['name', 'sub_id']);
$dupes = $collection->diff($colUnique);
我想要有相同的name
和sub_id
的模型。
id sub_id name
1 2 John
2 2 John <- duplicate
3 2 Robin <- unique
发布于 2019-04-16 20:35:43
您可以使用Collection.groupBy
方法。
$collection = \App\MyModel::all();
$collection
// Group models by sub_id and name
->groupBy(function ($item) { return $item->sub_id.'_'.$item->name; })
// Filter to remove non-duplicates
->filter(function ($arr) { return $arr->count()>1; })
// Process duplicates groups
->each(function ($arr) {
$arr
// Sort by id (so first item will be original)
->sortBy('id')
// Remove first (original) item from dupes collection
->splice(1)
// Remove duplicated models from DB
->each(function ($model) {
$model->delete();
});
})
发布于 2019-04-16 20:36:52
我最好的选择是DB::Query。
步骤1:按组通过获取数据
$uniqueData = DB::table('TABLE_NAME')
->groupBy(['sub_id', 'name'])
->select('id')
->toArray();
步骤2:删除重复记录.
$noOfDeletedRecords = DB::table('TABLE_NAME')
->whereNotIn($uniqueData)
->delete();
的优点: 1.只有2个查询2.比集合更好的性能。
https://stackoverflow.com/questions/55715895
复制相似问题