我正在使用Laravel 5.5,我想在向mysql中插入一组数据时排除重复记录。
例如,有一个表students
,它有这些字段:
id
name
gender
现在我要向students
中插入一组数据,如果不介意重复记录,我可以这样做:
public function insert()
{
$newStudents=[
['name'=>'Jim','gender'=>'boy'],
['name'=>'Lucy','gender'=>'girl'],
['name'=>'Jack','gender'=>'boy'],
['name'=>'Alice','gender'=>'girl']
];
DB::table('students')->insert($newStudents);
}
现在我不想插入重复的记录。(重复的是: name
和 gender
具有相同的值,没有一个字段具有相同的值) .
我该怎么办?
最佳答案
您可以使用 unique 收集助手。见下面的代码:
$newStudents=collect([
['name'=>'Jim','gender'=>'boy'],
['name'=>'Lucy','gender'=>'girl'],
['name'=>'Jack','gender'=>'boy'],
['name'=>'Alice','gender'=>'girl'],
['name'=>'Alice','gender'=>'girl']
])->unique(function ($student) {
return $student['name'].$student['gender'];
})->toArray();
DB::table('students')->insert($newStudents);
上面的代码只会插入唯一的记录,即使那里有重复的记录。
有关详细信息,请参见此处:https://laravel.com/docs/5.4/collections#method-unique
关于php - 拉维尔 : How to exclude duplicate records when inserting a group of data into mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082361/