php 使用 Eloquent 查找或创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20309033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:03:28  来源:igfitidea点击:

Find or Create with Eloquent

phplaravellaravel-4eloquent

提问by charleyh

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

我最近开始与工作Laravel口才,和不知道的是,缺乏一个查找或创建模型选项。你总是可以写,例如:

$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.

但是,难道没有更好的方法来查找或创建吗?在示例中似乎微不足道,但对于更复杂的情况,获取现有记录并更新它或创建新记录将非常有帮助。

回答by The Alpha

Below is the original accepted answer for: Laravel-4

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

There is already a method findOrFailavailable in Laraveland when this method is used it throws ModelNotFoundExceptionon fail but in your case you can do it by creating a method in your model, for example, if you have a Usermodel then you just put this function in the model

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

// 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();

If a user with idof 5exists, then it'll be updated, otherwise a new user will be created but the idwill be last_user_id + 1(auto incremented).

如果与用户id5存在,那么它就会被更新,否则新用户将被创建,但idlast_user_id + 1(自动递增)。

This is another way to do the same thing:

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

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

Instead of creating a static method, you can use a scopein the Model, so the method in the Modelwill be scopeMethodNameand call Model::methodName(), same as you did in the static method, for example

您可以scope在模型中使用 a 代替创建静态方法,因此ModelwillscopeMethodName和 callModel::methodName()中的方法与您在静态方法中所做的相同,例如

$user =  User::findOrCreate(5);

Update:

更新:

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

firstOrCreate是可用的Laravel 5x,答案是太旧,它被赋予了Laravel-4.02013

In Laravel 5.3, the firstOrCreatemethod has the following declaration:

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

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 Docs

API 文档

回答by Oliver Adria

Alternatively, in this case you can also use Laravel's function and search for id as an attribute, i.e.

或者,在这种情况下,您也可以使用 Laravel 的函数并搜索 id 作为属性,即

$user = User::firstOrCreate(['id' => $id]);

回答by Peter Gluck

Laravel 4 models have a built-in findOrNewmethod that does what you need:

Laravel 4 模型有一个内置findOrNew方法可以满足您的需求:

$user = User::findOrNew($id);

回答by Majbah Habib

Find or New based on primary key id

根据主键id查找或新建

$user = User::findOrNew($id); // if exist then update else insert
$user->name= $data['full_name'];
$user->save();

First or New based on non-primary key single filed

First 或 New 基于非主键单一归档

// get the record where field_name=value else insert new record
$user = User::firstOrNew(['field_name'=>'value']); 
$user->name= $data['full_name'];
$user->save();

First or New based on non-primary key multiple filed

First 或 New 基于非主键多次归档

// get the record where field_name1=value1 and field_name2=value2, else insert new record
$user = User::firstOrNew(['field_name1'=>'value1','field_name2'=>'value2']);
$user->name= $data['full_name'];
$user->save();

回答by Salar

In Laravel 5:
There are two methods you may use to create models by mass assigning attributes: firstOrCreateand firstOrNew.
The firstOrCreatemethod will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be insertedwith the given attributes.
The firstOrNewmethod, like firstOrCreatewill attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNewhas not yet been persisted to the database. You will need to call save manually to persist it:

在 Laravel 5 中:
您可以使用两种方法通过批量分配属性来创建模型:firstOrCreatefirstOrNew
firstOrCreate方法将尝试使用给定的列/值对定位数据库记录。如果在数据库中找不到该模型,则将插入具有给定属性的记录。
firstOrNew方法,likefirstOrCreate将尝试在数据库中查找与给定属性匹配的记录。但是,如果没有找到模型,则会返回一个新的模型实例。请注意,由 返回的模型firstOrNew尚未持久化到数据库中。您需要手动调用 save 来保存它:

// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

回答by Mahmoud Zalt

You can use firstOrCreate (It's working with Laravel 4.2)

您可以使用 firstOrCreate (它与 Laravel 4.2 一起使用)

$bucketUser = BucketUser::firstOrCreate([
    'bucket_id' => '1',
    'user_id'   => '2',
]);

returns found instance or new instance.

返回找到的实例或新实例。