Can't get Laravel associate to work

大憨熊 提交于 2019-11-30 11:05:52

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.

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();

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);

Edit: It may not be necessary to save the user model first but I've just always done that, not sure why.

As I understand it, ->associate() can onyl be called on a BelongsTo relationship. So, in your example, you could do $customer->user()->associate($user). However, in order to 'associate' a Has* relationship you use ->save(), so your code should be $user->customer()->save($customer)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!