Laravel 4.2 - 使用:: firstOrCreate并确定实际发生了什么?

时间:2015-01-14 01:12:18

标签: php laravel eloquent

在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的理解不正确,请帮助我更好地理解它。

正如我所提到的,我有兴趣知道是否有办法确定是否发生了新记录的创建?

1 个答案:

答案 0 :(得分:9)

该模型具有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...
}