gpt4 book ai didi

php - 在 Laravel 中,有没有办法找出 `firstOrCreate` 是否已创建或是否找到了该行?

转载 作者:IT王子 更新时间:2023-10-28 23:49:41 25 4
gpt4 key购买 nike

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

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

最佳答案

如果您在当前生命周期中创建模型,则模型的 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);

关于php - 在 Laravel 中,有没有办法找出 `firstOrCreate` 是否已创建或是否找到了该行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com