【问题标题】:In Laravel, is there a way to find out whether `firstOrCreate` created or if it found the row?在 Laravel 中,有没有办法找出是否创建了 `firstOrCreate` 或者是否找到了行?
【发布时间】:2016-08-01 07:22:21
【问题描述】:

在 Laravel 中,有没有办法区分 firstOrCreate 创建行和是否从之前找出行存在?

还是我必须先手动执行get(),然后再创建行?

【问题讨论】:

标签: php laravel laravel-5 eloquent


【解决方案1】:

如果您在当前生命周期中创建了模型,则模型的wasRecentlyCreated 属性将设置为true。否则,该属性将设置为false

换句话说,假设您有一个电子邮件用户bob@example

$user = User::firstOrCreate(['email' => 'bob@example.com']);

// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);

现在,假设new@example.com 不存在。

$user2 = User::firstOrCreate(['email' => 'new@example.com']);

// the below will dump out true because this user was created
// in the current request lifecycle
var_dump($user2->wasRecentlyCreated);

【讨论】:

  • 很好吃
  • Brilliant Laravel 已经涵盖了所有内容。
猜你喜欢
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
相关资源
最近更新 更多