INSERT IGNORE using Laravel's Fluent

前端 未结 10 1321
执笔经年
执笔经年 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:59

    Add the follow method insertIgnore to your Model

    usesTimestamps()) {
                $model->updateTimestamps();
            }
    
            $attributes = $model->getAttributes();
    
            $query = $model->newBaseQueryBuilder();
            $processor = $query->getProcessor();
            $grammar = $query->getGrammar();
    
            $table = $grammar->wrapTable($model->getTable());
            $keyName = $model->getKeyName();
            $columns = $grammar->columnize(array_keys($attributes));
            $values = $grammar->parameterize($attributes);
    
            $sql = "insert ignore into {$table} ({$columns}) values ({$values})";
    
            $id = $processor->processInsertGetId($query, $sql, array_values($attributes));
    
            $model->setAttribute($keyName, $id);
    
            return $model;
        }
    }
    

    You can use:

    App\User::insertIgnore([
        'name' => 'Marco Pedraza',
        'email' => 'mpdrza@gmail.com'
    ]);
    

    The next query it will be executed:

    insert ignore into `users` (`name`, `email`, `updated_at`, `created_at`) values (?, ?, ?, ?)
    

    This method automatically add/remove the Eloquent timestamps if you have enabled or disabled.

提交回复
热议问题