我需要删除 mysql 表上特定手机号码的重复行。我怎样才能用 Laravel 查询做到这一点?
最佳答案
如果您想在“名称”列中查找重复值,您也可以执行以下操作:
示例:
$duplicateRecords = DB::select('name')
->selectRaw('count(`name`) as `occurences`')
->from('users')
->groupBy('name')
->having('occurences', '>', 1)
->get();
然后您需要遍历您的集合并删除项目。foreach($duplicateRecords as $record) {
$record->delete();
}
更新 Laravel 8user
中的示例记录 table :ID
姓名
1
卡米拉·奥康纳
2
卡米拉·奥康纳
3
卡米拉·奥康纳
4
古西·狄更斯先生四世
5
耐心雅各布斯
6
耐心雅各布斯
查找字段的重复记录
name
你可以使用这个:$duplicated = DB::table('users')
->select('name', DB::raw('count(`name`) as occurences'))
->groupBy('name')
->having('occurences', '>', 1)
->get();
这将为您提供重复的值和重复的数量:Illuminate\Support\Collection {#274 ▼
#items: array:2 [▼
0 => {#277 ▼
+"name": "Camilla O'Conner"
+"occurences": 3
}
1 => {#278 ▼
+"name": "Patience Jacobs"
+"occurences": 2
}
]
}
现在您可以循环执行此操作并删除记录:foreach ($duplicated as $duplicate) {
User::where('name', $duplicate->name)->delete();
}
关于php - 如何删除 Laravel 中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206039/