Zubair
Zubair

Reputation: 295

I want to make many to many relationship using laravel Model

I am trying to make many to many relationships b/w three table I don't know how to make that please confirm me my relationship correct or not.

Project table

id | name

user table

id | name

project_assign

id | user_id | project_id

User Model

public function project_assign()
{
    return $this->belongsToMany('App\Project_assign','project_assign','user_id','id');
}

project_assign Model

public function user()
{
    return $this->belongsToMany('App\User','Project_assign','user_id','id');
}

Project Model

public function project_assign()
{
    return $this->belongsToMany('App\Project_assign','project_assign','project_id','id');
} 

Upvotes: 2

Views: 145

Answers (1)

Dilip Hirapara
Dilip Hirapara

Reputation: 15316

you don't need to make a relation in project_assign model. only Project and User will have relation,

Project Model

public function users(){
   return $this->belongsToMany('App\User','project_assign','project_id','user_id');
} 

User Model

public function projects(){
    return $this->belongsToMany('App\Project','project_assign','user_id','project_id');
}

In controller you can get like this

User::with('projects')->get();
Project::with('users')->get();

Upvotes: 1

Related Questions