将模型相互关联 Laravel
Posted
技术标签:
【中文标题】将模型相互关联 Laravel【英文标题】:Associate models with eachother Laravel 【发布时间】:2018-12-03 10:56:47 【问题描述】:我有这个if语句,如果没有给用户添加$address信息,则创建,否则继续。
public function getIndexEditClient(Request $request, $id)
$regions = DB::table("regions")->pluck("name","id");
$address = Address::where('id', $request->address_id)->with('region')->first();
if(empty($address))
$address = Address::create([
'street_name',
'house_number',
'postcode',
'city_id',
'country_id',
'region_id'
]);
// assiociate address with user
//then save it
else
$data = $this->data->getEditClient($id);
$admins = $this->data->getAdmin();
return view('client.edit', [
'client' => $data,
'admins' => $admins,
'regions' => $regions,
'address' => $address
]);
唯一的事情是,我必须将用户(客户端)与地址@注释行相关联。我不让它工作。
【问题讨论】:
【参考方案1】:试试这个:
$user->address()->associate($address);
$user->save();
【讨论】:
我认为问题出在create数组中。以上是关于将模型相互关联 Laravel的主要内容,如果未能解决你的问题,请参考以下文章