Reputation: 6740
I am working on an internal PMS, where I have four models: User
, Company
, Client
and Project
.
One Company
will have multiple Users
, and through the Company
, the User
will have access to many Clients
and Projects
. Nothing fancy here, just a classic PMS with company, clients, users and projects.
The User
model has a company_id
field (one user can only be related to one company at the moment). The Client
model also has a company_id
field. With this I thought I could have a HasManyThrough
relationship for User
and Client
, and I tried this:
public function clients()
{
return $this->hasManyThrough( Client::class, Company::class );
}
However, this returns the
SQLSTATE[HY000]: General error: 1 no such column: companies.user_id (SQL:
select "clients".*, "companies"."user_id" as "laravel_through_key" from "clients" inner join "companies" on "companies"."id" = "clients"."company_id" where "companies"."user_id" = 1 and "clients"."deleted_at" is null
In my database, companies.user_id
doesn't exist, because this relation is defined by users.company.id
. Would it be better to write a raw SQL query?
Upvotes: 0
Views: 47
Reputation: 666
Or may just use two relations like:
// User Model
[.....]
public function company()
{
return $this->belongsTo( Company::class, [YOUR_FK_HERE] );
}
public function clients()
{
return $this->company->clients();
}
[....]
and in the Company Model
// Company Model
[....]
public function clients()
{
return $this->hasMany( Client::class, [YOUR_FK_HERE] );
}
[....]
Upvotes: 1