如果不存在则插入新记录,如果存在则不更新,laravel eloquent

时间:2015-11-26 03:37:18

标签: laravel

如果不存在,我是否应该使用create方法插入新记录,如果存在则不更新记录?感谢。

2 个答案:

答案 0 :(得分:7)

使用firstOrCreate方法:

$user = User::firstOrCreate(['name' => 'John Doe']);

如果您想知道用户是创建还是获取,请检查wasRecentlyCreated属性:

if ($user->wasRecentlyCreated) {
    // "firstOrCreate" didn't find the user in the DB, so it created it.
} else {
    // "firstOrCreate" found the user in the DB and fetched it.
}

答案 1 :(得分:2)

在Laravel 5.2中,您使用Builder.php中的updateOrCreate方法,它使用firstOrNew方法验证db中是否存在给定属性并使用给定值更新记录或创建并保存新记录。

奇怪的是updateOrCreate没有出现在文档中:

https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models

/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function updateOrCreate(array $attributes, array $values = [])
{
    $instance = $this->firstOrNew($attributes);

    $instance->fill($values)->save();

    return $instance;
}
相关问题