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?
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.
See my response in http://laravel.io/forum/03-04-2014-hasmanythrough-with-many-to-many
Laravel I think not support this. See a hack at http://damien-louvard.fr/laravel-extends-model-hasmanythrough-3-parameters/
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community