如何在Laravel中删除重复的行 [英] How to Remove Duplicate Rows in Laravel
本文介绍了如何在Laravel中删除重复的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要删除mysql表上指定手机号码的重复行.如何使用Laravel查询做到这一点?
I need to delete duplicated rows for specified Mobile Number on a mysql table. How can I do this with an Laravel query?
推荐答案
如果您想在名称"列中找到重复的值,也可以执行以下操作:
You could also do something like this, if you want to find duplicate values in the column 'name':
示例:
$duplicateRecords = DB::select('name')
->selectRaw('count(`name`) as `occurences`')
->from('users')
->groupBy('name')
->having('occurences', '>', 1)
->get();
然后,您需要遍历集合并删除项目.
Then you need to loop through your collection and delete the items.
foreach($duplicateRecords as $record) {
$record->delete();
}
更新Laravel 8
user
表中的示例记录:
id | 名称 |
---|---|
1 | Camilla O'Conner |
2 | Camilla O'Conner |
3 | Camilla O'Conner |
4 | 先生.Gussie Dickens IV |
5 | 忍耐雅各布斯 |
6 | 忍耐雅各布斯 |
要查找字段 name
的重复记录,可以使用以下方法:
To find duplicate records for the field name
you can use this:
$duplicated = DB::table('users')
->select('name', DB::raw('count(`name`) as occurences'))
->groupBy('name')
->having('occurences', '>', 1)
->get();
这将为您提供重复的值和重复的数量:
This will give you the value that is duplicated and the amount of duplicates:
Illuminate\Support\Collection {#274 ▼
#items: array:2 [▼
0 => {#277 ▼
+"name": "Camilla O'Conner"
+"occurences": 3
}
1 => {#278 ▼
+"name": "Patience Jacobs"
+"occurences": 2
}
]
}
现在您可以循环浏览并删除记录:
Now you can cycle through this and delete the records:
foreach ($duplicated as $duplicate) {
User::where('name', $duplicate->name)->delete();
}
这篇关于如何在Laravel中删除重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文