当用户注册时,如何将行插入到多个表中。
我有基本的 Laravel 用户表。我还有一个企业表(id、business_name)和一个 usersbusinesses 表(id、user_id、business_id)
首先,我需要创建(数据库插入)用户并获取其生成的 id 值。
然后,我需要创建(数据库插入)业务并获取其生成的 id 值。
最后,我需要使用上面的值(user_id 和business_id)在 usersbusinesses 表中创建(数据库插入)一行
我知道我必须修改 app/Services/Registrar.php 文件,我只是不知道如何解决这个问题。当前代码仅插入到用户表中:
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
public function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
谢谢 克里斯蒂安
最佳答案
如果您想要执行更多操作,只需添加到刚刚粘贴的创建函数即可。
/**
* Create a new user instance after a valid registration and do more.
*
* @param array $data
* @return User
*/
public function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$business = Business::create([
'name' => 'best business ever'
]);
$business->owners()->sync([$user->id]);
return $user;
}
对于倒数第二部分:
$business->owners()->sync([$user->id]);
您应该阅读有关 Eloquent 关系的内容 here .
因为您要将这么多命令放在一起,所以我建议您阅读 Laravel 的作业/命令。 Queues section 中提到了它们Laravel 文档。
更新如何添加owner()方法。
Business.php 模型:
/**
* Owners of the business.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function owners()
{
return $this->belongsToMany('App\User', 'userbusinesses');
}
在您的 Users.php 模型中类似:
/**
* Business this person owns.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function businesses()
{
return $this->belongsToMany('App\User', 'userbusinesses');
}
但是,我的建议是保持符合标准,并将数据透视表重命名为business_user,在这种情况下,您不需要belongsToMany 中的第二个参数。
另请注意,我将保存命令更改为同步。我第一次没有意识到这是多对多。
关于php - Laravel 5 - 如何在用户注册时将行插入到多个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31081217/