INSERT IGNORE using Laravel's Fluent

前端 未结 10 1300
执笔经年
执笔经年 2020-12-11 02:12

Is there a quick way to modify a SQL query generated by Laravel\'s Fluent to have an INSERT IGNORE instead of the usual INSERT?

I\'m trying

10条回答
  •  情歌与酒
    2020-12-11 02:48

    Try this magic, in your model:

    public static function insertIgnore($array){
        $a = new static();
        if($a->timestamps){
            $now = \Carbon\Carbon::now();
            $array['created_at'] = $now;
            $array['updated_at'] = $now;
        }
        DB::insert('INSERT IGNORE INTO '.$a->table.' ('.implode(',',array_keys($array)).
            ') values (?'.str_repeat(',?',count($array) - 1).')',array_values($array));
    }
    

    Use like this:

    Shop::insertIgnore(array('name' => 'myshop'));
    

    This is a great way to prevent constraint violations that may occur with firstOrCreate in a multi-user environment, if that 'name' property was a unique key.

提交回复
热议问题