欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Find or Create with Eloquent findorcreate 自定义的方法 是以 id 为查找的根本 有大用

与 firstOrcreate 或 firstOrNew (它们是 laravel 内置的方法 )不同

firstOrcreate 或 firstOrNew 的参数是键值的数组 比如  TuiguangEffect::firstOrNew(['name' => 'Flight 10'])



Find or Create with 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.

shareimprove this questionedited Dec 2 '13 at 17:30The Alpha98.7k16173213asked Dec 1 '13 at 5:26charleyh1,34021331

   I am not an Eloquent expert, however even if there is no such method, most probably you can define it in an abstract class or trait that all of your models extend / make use of. – bagonyi Dec 1 '13 at 5:31

6 Answers 正确答案

Below is the original accepted answer for: laravel-4

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

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;}

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

$user =  User::findOrCreate(5);

Update:

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

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 Docs

shareimprove this answeredited May 23 at 12:10Community♦11answered Dec 1 '13 at 6:40The Alpha98.7k16173213

   findOrCreate doesn't exist in Laravel 5x, as you cannot create something using only the ID. I think what you are referring to is findOrNew. – SteveEdson Mar 3 '16 at 11:15   Right @SteveEdson but it's firstOrCreate :-) – The Alpha Mar 3 '16 at 12:09 

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

$user = User::firstOrCreate(['id' => $id]);
shareimprove this answeranswered Mar 27 '14 at 9:33Oliver Adria736615

   Docs for 4: laravel.com/api/4.1/Illuminate/Database/Eloquent/… – everyman Sep 21 '15 at 10:26   Docs for 5: laravel.com/api/5.1/Illuminate/Database/Eloquent/… – everyman Sep 21 '15 at 10:27

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

$user = User::findOrNew($id);
shareimprove this answeranswered Oct 27 '14 at 6:19Peter Gluck5,99212633

   note find or new instantiates an object but you still need to use save() function – Gokigooooks Feb 25 '16 at 11:17

In Laravel 5:
There are two methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew
The firstOrCreate method 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 inserted with the given attributes.
The firstOrNew method, like firstOrCreate will 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 firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:

// 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']);
shareimprove this answeranswered Feb 24 '16 at 9:04Salar1,9831429

Find or New based on primary key 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

// 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

// 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();
shareimprove this answeredited Aug 14 '16 at 11:02answered Aug 10 '16 at 6:38Majbah Habib1,0831114

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

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

returns found instance or new instance.

shareimprove this answeranswered Oct 15 '15 at 17:45Mahmoud Zalt9,00624348

来自 https://stackoverflow.com/questions/20309033/find-or-create-with-eloquent

普通分类: