我有2个表(用户和公司) . 用户具有不同的角色(购物者,分销商,管理员......) . 我有一个适合购物者的工作解决方案,部分适用于经销商 . 我在使用eloquent设置分销商用户的第二个关系时遇到了问题 . 在用户表中,我为购物者提供了company_id密钥 . 在公司表中,我有经销商的main_distributor_id密钥
关系:一家公司可以有多个购物者用户 . 一个购物者用户可以被分配到一个公司 .
一家公司可以有一个经销商 . 一个经销商可以与多家公司签约 .
用户模型:
/* used for shoppers */
public function company() {
return $this->belongsTo(Company::class);
}
/* what is the proper naming? */
public function mainDistributorCompanies() {
return $this->belongsTo('App\Company','main_distributor_id','id');
}
公司型号:
/* for shopper users.. */
public function users() {
return $this->hasMany(User::class, 'company_id');
}
/* What is the proper naming */
public function mainDistributorUsers() {
return $this->hasOne('App\User','id','main_distributor_id');
}
公司控制人:
public function index(Request $request) {
/* is this the correct way to include the relationship? Naming? */
$companies = Company::with('mainDistributorUsers')->get();
return view('companies/index', compact('companies'));
}
公司指数观点:
@foreach($companies as $company)
<tr>
<td>{{ $company->index }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->address }}</td>
<td>{{ $company->mainDistributorUsers->username }}</td> // error
<td>{{ $company->mainDistributorUsers()->username }}</td> // error
<td>{{ $company->username }}</td> // empty
</tr>
@endforeach
我为经销商选择了错误的关系吗?错误的命名?
1 回答
您必须检查没有
mainDistributorUsers
的公司:或者使用optional()助手:
顺便说一句:
mainDistributorUsers()
应该是BelongsTo
关系: