Support the ongoing development of Laravel.io →
Database Eloquent

I have this structure in my application.

table users:
  id,
  username

table projects:
  id,
  name

table project_users:
  project_id, // foreign key to projects.id
  user_id, // foreign key to users.id
  user_role

So I would like the users will have many projects through project_users table, then I write these in User class

	public function projects()
	{
		return $this->hasManyThrough('Project', 'ProjectUsers', 'user_id', 'project_id');
	}

but the problem is that this will have the query of following : SQL: select projects.*, project_users.user_id from projects inner join project_users on project_users.id = projects.project_id where project_users.user_id = 1

as you can see, even if my project_users table have the id field, the join clause is wrong, it should be on project_users.project_id=project.id

so How can I get the user's projects through the project_users table?

Last updated 3 years ago.
0

It looks to me that you really need a belongsToMany() with some extra consideration for the user_role property, something like:

public function projects()
{
    return $this->belongsToMany('Project')->withPivot('user_role');
}

hasManyThrough() is just shortcut for jumping across two One-to-Many relationships. For example, a User has many Posts and a Post has many Comments. You could set up a hasManyThrough() relationship to see all of the Comments made on all Posts by a User.

Hope this helps.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

steve3d steve3d Joined 21 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.