[英]Saving Multiple Data into Database from Different Controllers - Laravel
I am have two different controllers, user and company . 我有两个不同的控制器,用户和公司。 I want to save the data from user controller and company controller at the same time. 我想同时保存来自用户控制器和公司控制器的数据。 Is it a good practice to combine the store method from company controller in the user controller? 在用户控制器中结合公司控制器的存储方法是一种好习惯吗?
User Controller 用户控制器
$user = new User(array(
'name' => $request->get('name'),
));
$user->save();
$company = new Company(array(
'name' => $request->get('name'),
));
$company->save();
If you have the relationship set up correctly you can: 如果您已正确建立关系,则可以:
$user = \App\User::create([
"name" => $request->name,
"company_id" => \App\Company::create([
"name" => $request->name
])->id
]);
Assuming you have company_id
in your users
table, and inside your User model: 假设您的users
表中以及用户模型中都有company_id
:
public function company() {
return $this->hasOne(Company::class);
}
It would be fine to save both the company & user in the UserController. 将公司和用户都保存在UserController中会很好。 The best approach would be to use Eloquent Relations and wrapping both saves in a transaction. 最好的方法是使用Eloquent Relations,并将两个保存都包装在事务中。
\DB::transaction(function() {
$user->save();
$user->company()->save($company);
});
Or another approach: 或另一种方法:
$user->setRelation('company', $company)->push()
The magic of push()
will save the User & Company in one-go. push()
的神奇之处在于可以一次性保存User&Company。
Store the user and the company first 首先存储用户和公司
$user = new User();
$user->name = $request->name;
$user->save();
$company = new Company();
$company->name = $request->name;
$company->save();
then, look at your relation 然后,看看你的关系
if one user can have one company(in company's table has user_id) 如果一个用户可以拥有一个公司(在公司表中有user_id)
$user->company()->save($company);
or
$company->user()->associate($user);
if one company can have one user(in user's table has company_id) 如果一个公司可以有一个用户(在用户表中有company_id)
$company->user()->save($user);
or
$user->company()->associate($company);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.