Jay Ar Enrique
Jay Ar Enrique

Reputation: 69

Laravel: How to make a relationship between two table that has a reference table

I have 3 tables.

People, Assignments and Projects

each person in People table can be assigned to one or more Projects. Each project in Projects table can have one ore more person assigned to it.

Here are the columns of each table:

People

Assignments:

Projects

My question is: in my Project model, how do I define the relationship?

What I want is to be able to get the names of all person assigned to a specific project.

I NEED:

$project->assignedPeople

So I can:

foreach($projects as $project)
$project->title
  foreach(projects->assignedPeople as $person)
  $person->name

I NEED YOUR HELP PLEASE THANK YOU!

Upvotes: 1

Views: 6380

Answers (2)

ajith mohan
ajith mohan

Reputation: 527

// Inside Model Project
class Project extends Model {
    
    public function people()
    {
        return $this->hasMany('App\Models\People');
    }
    
}
    
// Inside Model People
class People extends Model {
    
    public function project()
    {
        return $this->belongsToMany('App\Models\Project');
    }    

}

// In case of custom joining table:
class People extends Model {
    
    public function project()
    {
         return $this->belongsToMany('App\Models\Project', 'Assignments', 'person_id', 'project_id');
    }
    
}

Upvotes: 0

Emran
Emran

Reputation: 51

Actually You need Many-to-Many relationship.

You can define the Models like this

Project Model

class Project extends Model {

    public function peoples()
    {
        return $this->belongsToMany('App\People');
    }
}

And

People Model

class People extends Model {

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

Now you can access the names of all person assigned to a specific project like this.

$project->peoples

And you can run your foreach loop like this

foreach($projects as $project) {
    echo $project->title;
    foreach(project->peoples as $person) {
        echo $person->name;
    }
}

Hope it may solve your problem.

Thanks

Upvotes: 1

Related Questions