baguus

Multiple relationships between same tables.. naming and syntax

Posted 11 months ago by baguus

Hi everyone, 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>{{ $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

Did I choose the wrong relationship for distributors? Wrong naming?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.