我不太确定我是否理解了Laravel中的associate方法。我理解这个想法,但我似乎不能让它起作用。
使用这个(提炼的)代码:
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 Illuminate\Database\Query\Builder::associate()。
据我所知,我完全按照文档中的说明来做。
我做错了什么?
发布于 2014-10-02 20:32:38
我必须承认,当我第一次开始使用Laravel时,我不得不一直参考文档的部分关系,即使在某些情况下,我也不是很正确。
为了帮助您,我们使用associate()来更新belongsTo()关系。从您的代码中可以看出,从$user->customer()返回的类是一个关联关系类,上面没有hasOne方法。
如果你反其道而行之。
$user = new User($data);
$customer = new Customer($customerData);
$customer->user()->associate($user);
$customer->save();因为$customer->user()是一个belongsTo关系,所以它可以工作。
反过来,您需要先保存用户模型,然后将customer模型保存到其中,如下所示:
$user = new User($data);
$user->save();
$customer = new Customer($customerData);
$user->customer()->save($customer);编辑:可能没有必要先保存用户模型,但我总是这样做,不知道为什么。
发布于 2014-10-02 20:32:31
据我所知,只能在BelongsTo关系上调用->associate()。因此,在您的示例中,您可以执行$customer->user()->associate($user)。但是,为了“关联”Has*关系,您需要使用->save(),因此您的代码应该是$user->customer()->save($customer)
https://stackoverflow.com/questions/26160661
复制相似问题