Can't get Laravel associate to work

前端 未结 2 1071
刺人心
刺人心 2021-01-01 12:03

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:

2条回答
  •  时光说笑
    2021-01-01 12:27

    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.

提交回复
热议问题