不能让Laravel的助理工作 [英] Can't get Laravel associate to work
问题描述
如果我了解关联方法,我不太确定在拉里维尔。我理解这个想法,但我似乎无法让它工作。
I'm not quite sure if I understand the associate method in Laravel. I understand the idea, but I can't seem to get it to work.
使用(蒸馏)代码:
class User
{
public function customer()
{
return $this->hasOne('Customer');
}
}
class Customer
{
public function user()
{
return $this->belongsTo('User');
}
}
$user = new User($data);
$customer = new Customer($customerData);
$user->customer()->associate($customer);
我得到一个调用未定义的方法Illuminate\Database\Query\\ \\Builder :: associate()
当我尝试运行这个。
I get a Call to undefined method Illuminate\Database\Query\Builder::associate()
when I try to run this.
从我可以看到,我完全按照文件。
From what I can read, I do it exactly as is stated in the docs.
我做错了什么?
推荐答案
我不得不承认当我第一次开始使用Laravel的关系时,我不得不一直参考文档,甚至在某些情况下,我没有得到正确的。
I have to admit that when I first started using Laravel the relationships where the part that I had to consistently refer back to the docs for and even then in some cases I didn't quite get it right.
为了帮助您, associate()
用于更新 belongsTo()
关系。看看你的代码,从 $ user-> customer()
返回的类是一个 hasOne
关系类,没有关联方法。
To help you along, associate()
is used to update a belongsTo()
relationship. Looking at your code, the returned class from $user->customer()
is a hasOne
relationship class and will not have the associate method on it.
如果你要做的另一回事。
If you were to do it the other way round.
$user = new User($data);
$customer = new Customer($customerData);
$customer->user()->associate($user);
$customer->save();
它可以作为 $ customer-> user()
是一个 belongsTo
关系。
It would work as $customer->user()
is a belongsTo
relationship.
要做到这一点,首先保存用户模型,然后将客户模型保存为:
To do this the other way round you would first save the user model and then save the customer model to it like:
$user = new User($data);
$user->save();
$customer = new Customer($customerData);
$user->customer()->save($customer);
编辑:可能没有必要先保存用户模型,但我一直都这样做,不知道为什么。
It may not be necessary to save the user model first but I've just always done that, not sure why.
这篇关于不能让Laravel的助理工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!