php - 拉维尔 : How to exclude duplicate records when inserting a group of data into mysql?

标签 php mysql laravel

我正在使用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);
}

现在我不想插入重复的记录。(重复的是: namegender 具有相同的值,没有一个字段具有相同的值) .

我该怎么办?

最佳答案

您可以使用 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/

相关文章:

php - 单击时如何使我的删除链接拆分为是/否?

php - 如何用数据库中的数据填充复选框?

php - 无法正确匹配 URI 字符串中的 "-"

php - 在创建配置文件时覆盖配置文件 - Prestashop

c# - 如何在 C# 中创建 MySql 函数?

php - 如何在 Laravel 中按 $category->companies 进行分页

php - RequestException.php 中的 ServerException 第 107 行 : 500 Internal Server Error

php - Docker和php “standard_init_linux.go:207: exec user process caused ” exec格式错误”。入口点也无法读取exec的参数

mysql - MYSQL 每年增加一列

laravel - Vuetify 组件导入问题