Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Eloquent hasManyThrough, access One->Many->One

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading