[英]How to save relationship between 2 tables
How to save data from the one form to two tables and save relationship between them?如何将一个表格中的数据保存到两个表格中并保存它们之间的关系?
I have model Company:我有模型公司:
public function maps()
{
return $this->belongsTo('App\Map');
}
and model Map:和模型图:
public function companies()
{
return $this->hasOne('App\Company');
}
and form with inputs:并带有输入的表单:
and mysql tables:和 mysql 表:
and store:并存储:
public function store(CreateCompanyFormRequest $request)
{
$input = Request::all();
$company = new Company($request->all());
Auth::user()->companies()->save($company);
$lat = $request->input('lat');
$long = $request->input('long');
$maps = new Map([
'lat' => $lat,
'long' => $long
]);
$maps->save();
return $input;
}
How to save relationship between Comapny and Map (company_id and map_id)?如何保存Comapny和Map的关系(company_id和map_id)? Best thanks!
最好的感谢! :)
:)
Since it's many-to-many relationship, use attach()
:由于它是多对多关系,因此使用
attach()
:
public function store(CreateCompanyFormRequest $request)
{
$company = auth()->user()->companies()->create($request->all());
$maps = Map::create($request-all());
$company->maps()->attach($map->id);
return back()->withInput();
}
If you are using pivot table company_map
first of all you should change your relationships:如果你首先使用数据透视表
company_map
你应该改变你的关系:
public function maps()
{
return $this->belongsToMany('App\Map');
}
and和
public function companies()
{
return $this->belongsToMany('App\Company');
}
and then you should add:然后你应该添加:
$maps->companies()->attach($company->id);
after:后:
$maps->save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.