如何将数据从一个表格保存到两个表格并保存它们之间的关系?
我有模特公司:
public function maps()
{
return $this->belongsTo('App\Map');
}
和模型Map:
public function companies()
{
return $this->hasOne('App\Company');
}
并输入表单:
和mysql表:
并存储:
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;
}
如何保存Comapny和Map(company_id和map_id)之间的关系? 非常感谢! :)
答案 0 :(得分:1)
由于它是多对多的关系,请使用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();
}
答案 1 :(得分:0)
如果你首先使用数据透视表company_map
,你应该改变你的关系:
public function maps()
{
return $this->belongsToMany('App\Map');
}
和
public function companies()
{
return $this->belongsToMany('App\Company');
}
然后你应该添加:
$maps->companies()->attach($company->id);
后:
$maps->save();