使用 Eloquent 查找或创建

Find or Create with Eloquent(使用 Eloquent 查找或创建)
本文介绍了使用 Eloquent 查找或创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我最近开始使用 Laravel 和 Eloquenta>,并且想知道缺少模型的查找或创建选项.你总是可以写,例如:

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

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

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 = 'John';
$user->last_name = 'Doe';
$user->save();

如果存在 id5 的用户,则更新该用户,否则将创建一个新用户,但 id将是 last_user_id + 1(自动递增).

If a user with id of 5 exists, 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中使用scope代替创建静态方法,所以Model中的方法将是scopeMethodName和调用Model::methodName(),就像你在静态方法中所做的一样,例如

Instead of creating a static method, you can use a scope in the Model, so the 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);

更新:

firstOrCreateLaravel 5x 中可用,答案太旧了,它在 2013 中为 Laravel-4.0 给出.

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 文档

这篇关于使用 Eloquent 查找或创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)