Saving related records in laravel

后端 未结 4 633
醉酒成梦
醉酒成梦 2020-12-13 00:14

I have users, and users belong to a dealership.

Upon user registration, I\'m trying to save a new user, and a new dealership.

User database has a de

4条回答
  •  生来不讨喜
    2020-12-13 00:43

    Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.

    Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:

    User Model:

    public function dealership()
    {
      return $this->belongsTo('Dealership');
    }
    

    Dealership Model:

    public function users()
    {
      return $this->hasMany('User');
    }
    

    To save a User from the Dealership perspective, you do this:

    $dealership->users()->save($user);
    

    To associate a dealership with a user, you do this:

    $user->dealership()->associate($dealership);
    $user->save();
    

提交回复
热议问题