I have 2 tables (users and companies). Users have different roles (shopper, distributor, administrator,...). I have a working solution for shoppers and partially for distributors. I'm having a problem using eloquent to setup the second relationship for distributor users. In users table I have company_id key for shoppers. In companies table I have main_distributor_id key for distributors
Relations: One company can have multiple shopper users. One shopper user can be asigned to one company.
One company can have one distributor. One distributor can be asigned to multiple companies.
User model:
/* 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');
}
Company model:
/* 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');
}
Companies controller:
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'));
}
Companies index view:
@foreach($companies as $company)
<tr>
<td></td>
<td></td>
<td></td>
<td></td> // error
<td></td> // error
<td></td> // empty
</tr>
@endforeach
Did I choose the wrong relationship for distributors? Wrong naming?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire