如果不存在则插入一条新记录,如果存在则不更新,laravel eloquent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33930164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert a new record if not exist and don't update if exist, laravel eloquent
提问by Adrian Cobb
Should I use create
method to insert a new record if doesn't exist and don't update the record if exist? Thanks.
如果create
不存在,我应该使用方法插入新记录,如果存在则不更新记录吗?谢谢。
回答by Joseph Silber
Use the firstOrCreate
method for that:
使用该firstOrCreate
方法:
$user = User::firstOrCreate(['name' => 'John Doe']);
If you want to know whether the user was created or fetched, check the wasRecentlyCreated
property:
如果您想知道用户是创建的还是获取的,请检查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.
}
回答by Carlos Torres
In Laravel 5.2 you have the updateOrCreate
method from Builder.php, it uses the firstOrNew
method to verify if the given attributes exists in db and update the records with the given values or create and save the new records.
在 Laravel 5.2 中,您有updateOrCreate
来自 Builder.php的方法,它使用该firstOrNew
方法来验证给定的属性是否存在于 db 中,并使用给定的值更新记录或创建并保存新记录。
The weird thing is that updateOrCreate
doesn't appear in the docs:
奇怪的是updateOrCreate
它没有出现在文档中:
https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models
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;
}