在Laravel 4.2中使用Model::firstOrCreate
时,是否有办法知道是先发生还是先发生?
让我解释一下,我的理解是::: firstOrCreate会创建一条记录(如果该记录不存在),或者返回包含参数数组数据的记录值。
所以,如果我有这样的事情:
// Auth::user()->id; returns 7
$person = Persons::firstOrCreate(array(
'approver' => 123,
'receiver' => Auth::user()->id,
'plan' => 'gold',
));
我有这些记录
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
128 | 7 | gold
____________________________________
123 | 7 | platinum
____________________________________
然后将创建一个新记录
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
128 | 7 | gold
____________________________________
123 | 7 | platinum
____________________________________
123 | 7 | gold
____________________________________
如果我再次运行以上代码,则不会创建新值,并且将返回此记录
approver | receiver | plan
____________________________________
123 | 7 | gold
____________________________________
但是如果我的代码看起来像这样
$person = Persons::firstOrCreate(array(
'approver' => 123,
'receiver' => Auth::user()->id
));
这些记录将被退回
approver | receiver | plan
____________________________________
123 | 7 | silver
____________________________________
123 | 7 | platinum
____________________________________
123 | 7 | gold
____________________________________
如果我对:: firstOrCreate的理解不正确,请帮助我更好地理解它。
正如我提到的,我很想知道是否有一种方法可以确定是否创建新记录?
最佳答案
该模型具有wasRecentlyCreated
属性:
$person = Persons::firstOrCreate([
'approver' => 123,
'receiver' => auth()->id(),
'plan' => 'gold',
]);
if ($person->wasRecentlyCreated) {
// $person was created
} else {
// $person was fetched
}
对于较旧的Laravel版本,您可以使用
firstOrNew
实现所需的功能:$person = Persons::firstOrNew([
'approver' => 123,
'receiver' => Auth::user()->id,
'plan' => 'gold',
]);
if (! $person->id) {
$person->save();
// $person was created...
} else {
// $person was fetched...
}