Laravel Eloquent-关系上的firstOrCreate() [英] Laravel Eloquent - firstOrCreate() on a relationship
问题描述
当我在另一个模型的关系上尝试firstOrCreate()
时,它不起作用:
When I try the firstOrCreate()
on a relationship of another model, it does not work:
Client::find($id)->users()->firstOrCreate(array('email' => $email));
这将返回一条错误消息
调用未定义的方法Illuminate \ Database \ Query \ Builder :: firstOrCreate()
Call to undefined method Illuminate\Database\Query\Builder::firstOrCreate()
虽然可以直接在模型User
上运行它.
Running this directly on the model User
will work though.
推荐答案
这行不通,您必须手动/直接使用User模型来执行此操作,因为users()应该返回一个集合对象
This won't work, you have to do it manually/directly using User model because users() should return a collection object
这是正确的,users()函数不会返回(新的,空的或已创建的)用户模型,而是返回一个集合对象.
This is correct, the users() function does not return a (new, empty or created) User model, it returns a collection object.
还记录了 http://laravel.com/docs/5.1 /eloquent-relationships#inserting-related-models (如果您使用的是laravel关系,则应该有效).
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.
您误解了该文档.关系对象具有create()方法和save()方法,但是关系对象不是完整的模型对象.要获得完整的User模型对象(例如firstOrCreate())的所有功能,则必须在模型对象上调用它们.
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);
请注意,可以直接从客户端模型的关系中将$ user对象保存在此处,即使它可能已经存在于此处,也应在执行此操作时只更新$ user对象上的client_id字段.
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.
这篇关于Laravel Eloquent-关系上的firstOrCreate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!