如何删除 Laravel 中的重复行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37206039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:47:38  来源:igfitidea点击:

How to Remove Duplicate Rows in Laravel

phplaravellaravel-5.2

提问by Karthik mathesh

I need to delete duplicated rows for specified Mobile Number on a mysql table. How can I do this with an Laravel query?

我需要删除 mysql 表上指定手机号码的重复行。我怎样才能用 Laravel 查询做到这一点?

回答by codedge

You could also do something like this, if you want to find duplicate values in the column 'name':

如果您想在“名称”列中查找重复值,您也可以执行以下操作:

Example:

例子:

$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();
}

回答by noodles_ftw

With Eloquent:

雄辩:

App\Model::where('mobile_number', '0123456789')->delete();

With the Query Builder:

使用查询生成器:

DB::table('some_table')->where('mobile_number', '0123456789')->delete();

EDIT

编辑

The above will delete allrows with mobile_number0123456789. If you want to keep one, use this:

以上将删除所有带有mobile_number0123456789. 如果你想保留一个,使用这个:

// 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();

回答by zarpio

If you would like to leave every single entry and delete other duplicates.

如果您想保留每个条目并删除其他重复项。

The easiest way I found.

我找到的最简单的方法。

$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();
}

回答by AlmostPitt

You could also try to map out all of the phone numbers within the entries and if the number comes up again, you delete it.

您还可以尝试映射条目中的所有电话号码,如果该号码再次出现,则将其删除。

For example:

例如:

$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']);
    }
}