Laravel Eloquent - 关系的 firstOrCreate()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23965615/
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
Laravel Eloquent - firstOrCreate() on a relationship
提问by Kousha
When I try the firstOrCreate()
on a relationship of another model, it does not work:
当我尝试firstOrCreate()
另一个模型的关系时,它不起作用:
Client::find($id)->users()->firstOrCreate(array('email' => $email));
This returns an error saying
这将返回一个错误说
Call to undefined method Illuminate\Database\Query\Builder::firstOrCreate()
调用未定义的方法 Illuminate\Database\Query\Builder::firstOrCreate()
Running this directly on the model User
will work though.
不过,直接在模型上运行它User
会起作用。
采纳答案by delatbabel
This won't work, you have to do it manually/directly using User model because users() should return a collection object
这行不通,您必须手动/直接使用 User 模型来完成,因为 users() 应该返回一个集合对象
This is correct, the users() function does not return a (new, empty or created) User model, it returns a collection object.
这是正确的, users() 函数不返回(新的、空的或创建的)用户模型,它返回一个集合对象。
It's also documented http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-modelsif you use the laravel relations than it should work.
如果您使用 laravel 关系而不是它应该工作,它还记录了http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models。
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.
您误解了该文件。关系对象有一个 create() 方法和一个 save() 方法,但是关系对象不是一个完整的模型对象。要获得完整用户模型对象(例如 firstOrCreate())的所有功能,您必须在模型对象上调用它们。
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.
请注意,从 Client 模型的关系中直接将 $user 对象保存在此处应该没问题,即使它可能已经存在于此处,但在您这样做时它应该只更新 $user 对象上的 client_id 字段。
回答by Julio Popócatl
This should do:
这应该做:
Client::find($id)->first()->users()->firstOrCreate(array('email' => $email));