I'm pretty new to laravel. Just practicing by trying to rewrite my project management tool but i can't seem to wrap my head around the hasManyThrough relationship (if it's even the right one).
Basis
I want every logged in user to have (manage) multiple projects and also every customer to have (commission) multiple projects.
Current structure:
user Database
- id
- ...
Model
public function projects(){
return $this->hasMany(Project::class);
}
customer Database
- id
- ...
Model
public function projects(){
return $this->hasMany(Project::class);
}
project Database
- id
- ...
- manager_id (foreign,references user.id)
- customer_id (foreign, references customer.id)
Model
public function manager(){
return $this->belongsTo(User::class);
}
public function customer(){
return $this->belongsTo(Customer::class);
}
Goal
I want to list my Users customers on the Dashboard. So every unique customer that commissioned a project, that the user is managing. I don't want to assign a customer directly to a user, because every project should have a manager, not the customer itself.
Tries
I did try to add the following to the User Model:
public function customers(){
return $this->hasManyThrough(Customer::class, Project::class);
}
but i get a error, saying that there is no project_id in the customer table, which of course there isn't.
Thank you in advance
CodePudding user response:
Since laravel can't guess that users == managers you have to define the key relationships yourself. Try this:
return $this->hasManyThrough(Customer::class, Project::class, 'manager_id', 'id', 'id', 'customer_id');
https://laravel.com/docs/9.x/eloquent-relationships#has-many-through-key-conventions