我需要在mysql表上删除指定移动号码的重复行。如何使用Laravel查询执行此操作?
答案 0 :(得分:6)
如果您想在“名称”列中找到重复值,您也可以这样做:
示例:强>
$duplicateRecords = DB::select('name')
->selectRaw('count(`name`) as `occurences`')
->from('users')
->groupBy('name')
->having('occurences', '>', 1)
->get();
然后你需要遍历你的收藏并删除这些项目。
foreach($duplicateRecords as $record) {
$record->delete();
}
答案 1 :(得分:4)
用Eloquent:
App\Model::where('mobile_number', '0123456789')->delete();
使用查询生成器:
DB::table('some_table')->where('mobile_number', '0123456789')->delete();
以上内容将删除mobile_number
0123456789
的所有行。如果你想保留一个,请使用:
// Get the row you don't want to delete.
$dontDeleteThisRow = App\Model::where('mobile_number', '0123456789')->first();
// Delete all rows except the one we fetched above.
App\Model::where('mobile_number', '0123456789')->where('id', '!=', $dontDeleteThisRow->id)->delete();
答案 2 :(得分:1)
您还可以尝试映射出条目中的所有电话号码,如果再次出现该号码,则将其删除。
例如:
$allContacts = Contact::all()->map->only(['mobile', 'id']);
$uniqueContacts = [];
foreach ($allContacts as $contact) {
if (in_array($contact['mobile'], $uniqueContacts)) {
Contact::where('id', $contact['id'])->delete();
} else {
array_push($uniqueContacts, $contact['mobile']);
}
}
答案 3 :(得分:0)
如果您想保留每一个条目并删除其他重复项。
我找到的最简单的方法。
$same_data = DB::table('table_name')->where('mobile_number', '0000000000');
if ($same_data->count() > 1) {
$same_data_before = clone $same_data;
$top = $same_data->first();
$same_data_before->where('id', '!=', $top->id)->delete();
}
答案 4 :(得分:0)
要删除重复项,但保留第一个或最后一个,请执行以下操作:
function foo(x: any) : string { /* code that must return a string */ }
答案 5 :(得分:-2)
这里我要删除重复的具有相同手机号码的用户
$users = DB::table('users')->get();
$users = $users->groupBy('mobile_no');
foreach ($roles as $key => $value){
if(count($value) >1){
$id = $value[0]->id;
$t = $value->where('id','!=',$id)->pluck('id');
User::whereIn('id',$t)->delete();
}
}