Laravel first或创建例外
问题描述:
比方说,我有一个下表:id |名称|电子邮件| create_date | creator_idLaravel first或创建例外
当我使用Laravel的firstOrCreate方法时,它会复制我的记录,因为每次调用create_date和creator_id参数都会被更改。有没有办法在检查数据库中已有的记录时忽略这些字段?
伪例子可能是这样的:firstOrCreate(array('name'=>'test', 'email'=>'[email protected]'), $exceptionsArray('create_date', 'creator_id'))
答
firstOrCreate()
方法接受一组属性,并且它基于来自那些返回或创建记录的属性的记录的存在。
例如:
| id | name | created_at |
| 1 | Joe | 2015-10-01 01:00:00 |
| 2 | Sam | 2015-10-01 01:00:00 |
| 3 | Ali | 2015-10-01 01:00:00 |
| 4 | Tom | 2015-10-01 01:00:00 |
$user = User::firstOrCreate(['name' => 'Joe']);
// $user = record with id 1
这是现有的用户,因为firstOrFail()
执行:
User::where('name', 'Joe')->first();
下一页例如:
$user = User::firstOrCreate(['name' => 'Joe', 'created_at' => '2015-10-01 01:00:00']);
// $user = record with id 1
这使用户返回,因为罩下的执行以下查询:
User::where('name', 'Joe')->where('created_at', '2015-10-01 01:00:00')->first();
$user = User::firstOrCreate(['name' => 'Joe', 'created_at' => '2020-10-01 01:00:00']);
// $user = a brand new user, as the created_at time is different
firstOrCreate()
方法所做的是检查记录是否存在您传递给它的属性。
所以,取最后一个例子,它之所以创造了一个新纪录,是因为它评价:
User::where('name', 'Joe')->where('created_at', '2020-10-01 01:00:00')->first();
这当然会失败。
总之,使用firstOrCreate
时,没有传递created_at
属性,因为始终是动态创建的,在很多情况下,你可能不希望包括creator_id
。
答
我不知道这是一个选择,但你可以只使用存在()方法您的查询是这样的:
if (Model::where('name', '=', 'test')->where('email', '=', '[email protected]')->exists()) {
// do something
} else {
// add new record
}
谢谢,它是有道理的 –