注册用户后,如何在多个表中插入行。
我有基本的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]);
您应该阅读有关雄辩的关系here。
因为您将这么多命令放在一起,所以建议您阅读Laravel的Jobs / Commands。 Laravel文档的Queues section中提到了它们。
更新有关如何添加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中的第二个参数。
另请注意,我将保存命令更改为同步。我没有意识到这是第一次多对多。
检查对象是否已在集合中-Laravel - php当我循环一系列不同的结果时,我希望将对象添加到新集合中。查询:$osRed = Item::where('category', 'Hardware') ->where(function ($query) { $query->where('operating_system', '…
PHP Laravel从另一个驱动器读取文件 - php我目前正在学习Laravel。我想知道是否有一种方法可以在Laravel中使用Storage::从另一个硬盘访问文件(使用Windows)。例如,我在驱动器C:上安装了带有Laravel的Xampp,但是我想访问网站目录之外的E:上的文件。我试过使用Storage::files('E:')和File::files('E:…
Laravel-foreach局部变量正在覆盖全局变量 - php今天,我面临一个非常奇怪的问题。我有一个控制器,将从该控制器向视图sections thread和threads发送三个变量。在我看来,我正在使用foreach循环遍历所有部分,如下所示:@foreach($sections as $i => $section) 对于每个部分,我都将创建一个div并给出如下的ID:id="{{ $thread…
Laravel-使用雄辩的语言在开始日期和结束日期之间选择行 - php我想将此查询转换为雄辩的laravel,select * from schedule where (now() between start_date and end_date); 我尝试使用whereBetween,但是出现了一些错误。$schedule = Schedule::whereBetween(Carbon::now(), ['start…
Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException - php我正在编写一些Laravel Blade模板,并且我的模型可能包含空对象。我非常想尝试获取对象属性,如果有错误,则返回null。因此,不必编写以下代码:@if ($model->child_object_that_may_be_null) {{ $model->child_object_that_may_be_null->interesti…