Laravel Eloquent - firstOrCreate() on a relationship

痴心易碎 提交于 2020-01-02 03:47:09

问题


When I try the firstOrCreate() on a relationship of another model, it does not work:

Client::find($id)->users()->firstOrCreate(array('email' => $email));

This returns an error saying

Call to undefined method Illuminate\Database\Query\Builder::firstOrCreate()

Running this directly on the model User will work though.


回答1:


This won't work, you have to do it manually/directly using User model because users() should return a collection object

This is correct, the users() function does not return a (new, empty or created) User model, it returns a collection object.

It's also documented http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models if you use the laravel relations than it should work.

You are misinterpreting that document. The relationship object has a create() method and a save() method, however the relationship object is not a full model object. To get all of the functionality of a full User model object (such as firstOrCreate()) then you have to call them on the model object.

So, for example, this code should work:

$user = User::firstOrNew(array('email' => $email));
Client::find($id)->users()->save($user);

Note that it should be OK to save the $user object here directly from the Client model's relationship, even though it may already exist here, it should just update the client_id field on the $user object when you do so.



来源:https://stackoverflow.com/questions/23965615/laravel-eloquent-firstorcreate-on-a-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!