Laravel 5.1 Create or Update on Duplicate

前端 未结 6 949
悲哀的现实
悲哀的现实 2020-12-03 01:29

In Laravel 5.1, for MySQL insert, I want to see if the record already exists and update on duplicate or create new if none exists.

I have already searched SO where t

6条回答
  •  悲哀的现实
    2020-12-03 01:41

    I created a package to work with MySQL insert on duplicate key.

    It may be useful for others:

    https://packagist.org/packages/yadakhov/insert-on-duplicate-key

    Example:

    /**
     * Class User.
     */
    class User extends Model
    {
        use Yadakhov\InsertOnDuplicateKey;
        ...
    }
    
    // associative array must match column names
    $users = [
        ['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One'],
        ['id' => 2, 'email' => 'user2@email.com', 'name' => 'User Two'],
        ['id' => 3, 'email' => 'user3@email.com', 'name' => 'User Three'],
    ];
    
    User::insertOnDuplicateKey($users);
    

提交回复
热议问题