問題描述
我不太確定我是否理解 associate 方法在 Laravel 中.我理解這個想法,但我似乎無法讓它發揮作用.
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.
使用這個(蒸餾)代碼:
With this (distilled) code:
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);
當我嘗試運行它時,我收到一個 Call to undefined method IlluminateDatabaseQueryBuilder::associate()
.
I get a Call to undefined method IlluminateDatabaseQueryBuilder::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.
如果你反過來做.
$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 助理工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!