在 laravel 中保存相关记录 [英] Saving related records in laravel
问题描述
我有用户,而用户属于经销商.
I have users, and users belong to a dealership.
在用户注册后,我正在尝试保存一个新用户和一个新经销商.
Upon user registration, I'm trying to save a new user, and a new dealership.
用户数据库有一个 dealership_id
列,我想用新创建的经销商的 ID 填充该列.
User database has a dealership_id
column, which I want to be populated with the ID of the newly created dealership.
这是我当前在 UserController
存储方法中的代码.
This is my current code in the UserController
store method.
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
尝试使用 $user->push();
用户数据已更新,但未创建或更新经销商.
Trying to use $user->push();
User data gets updated, but dealership is not created or updated.
推荐答案
Eloquent 的 push()
保存了模型和它的关系,但是首先你必须告诉你想在关系中涉及什么.
Eloquent's push()
saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.
由于您的 user-model/table 包含经销商的 id,我假设一个用户只能属于一个经销商,因此关系应该如下所示:
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:
用户模型:
public function dealership()
{
return $this->belongsTo('Dealership');
}
经销商模式:
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();
这篇关于在 laravel 中保存相关记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!