寻找或创造与雄辩 [英] Find or Create with Eloquent

查看:108
本文介绍了寻找或创造与雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 Laravel Eloquent ,并且想知道缺少模型的查找或创建选项。您可以随时写,例如:

I have recently started working with Laravel and Eloquent, and was wondering about the lack of a find or create option for models. You could always write, for example:

$user = User::find($id);
if (!$user) {
    $user = new User;
}

然而,没有更好的方法来找到或创建?在这个例子中似乎是微不足道的,但是对于更复杂的情况来说,获取现有记录并进行更新或创建新记录将是非常有帮助的。

However, is there not a better way to find or create? It seems trivial in the example, but for more complex situations it would be really helpfully to either get an existing record and update it or create a new one.

推荐答案

以下是原始的接受的答案: laravel-4

Below is the original accepted answer for: laravel-4

已经有一个方法 findOrFail 可在 Laravel 中使用,当使用此方法它将失败引发 ModelNotFoundException ,但在您的情况下,您可以通过在模型中创建一个方法来实现,例如,如果您有一个用户模型,那么你只需将这个函数放在模型中

There is already a method findOrFail available in Laravel and when this method is used it throws ModelNotFoundException on fail but in your case you can do it by creating a method in your model, for example, if you have a User model then you just put this function in the model

// Put this in any model and use
// Modelname::findOrCreate($id);
public static function findOrCreate($id)
{
    $obj = static::find($id);
    return $obj ?: new static;
}

从您的控制器,您可以使用

From your controller, you can use

$user =  User::findOrCreate(5);
$user->first_name = 'Jhon';
$user->last_name = 'Doe';
$user->save();

如果具有 id od 5 是exixts,那么它将被更新,否则将创建一个新用户,但$ code> id 将是 last_user_id + 1 (自动递增)。

If a user with id od 5 is exixts then it'll be updated, otherwise a new user will be created but the id will be last_user_id + 1 (auto incremented).

这是另一种做同样事情的方法:

This is another way to do the same thing:

public function scopeFindOrCreate($query, $id)
{
    $obj = $query->find($id);
    return $obj ?: new static;
}

而不是创建静态方法,您可以使用范围,因此 Model 中的方法将为 scopeMethodName 并调用 Model :: methodName(),与静态方法一样,例如

Instead of creating a static method, you can use a scope in the Model, so method in the Model will be scopeMethodName and call Model::methodName(), same as you did in the static method, for example

$user =  User::findOrCreate(5);



更新:



firstOrCreate Laravel 5x 中可用,答案太旧了,它被给予 Laravel-4.0 2013

Update:

The firstOrCreate is available in Laravel 5x, the answer is too old and it was given for Laravel-4.0 in 2013.

在Laravel 5.3中, firstOrCreate 方法具有以下声明:

In Laravel 5.3, the firstOrCreate method has the following declaration:

public function firstOrCreate(array $attributes, array $values = [])

这意味着你可以这样使用:

Which means you can use it like this:

User::firstOrCreate(['email' => $email], ['name' => $name]);

用户的存在只会通过电子邮件进行检查,但创建时,新记录将同时保存电子邮件和

User's existence will be only checked via email, but when created, the new record will save both email and name.

API文件

这篇关于寻找或创造与雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆