C
C
Constantine12017-04-22 09:04:00
Laravel
Constantine1, 2017-04-22 09:04:00

How to access related object fields in Laravel?

The project has two models: Department and Person. These models are defined with a many-to-many relationship. that is, each Person can own multiple Departments, and each Department can own multiple Persons.
For person:

class Person extends Model
{
    protected $table = 'persons';
    public function departments (){
        return $this->belongsToMany('App\Department')->withTimestamps();
    }
}

For department:
class Department extends Model
{
    public function persons(){
        return $this->belongsToMany('App\Persons')->withTimestamps();
    }
}

Let's take a certain Person:
$person = App\Person::find(10);
define for him
$person->departments()->attach(1,5);
As a result, we get a record in the pivot table.
we write:
$person->toArray();
return $person->departments;

Let's get an array of departments bound to Person
Now, the question is: how to get a list of Persons that are bound to it through the Department model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hakkol, 2017-04-22
@hakkol

If you want to get a list of Persons that have a relationship with Department then
If you want to get all persons for a particular department then:
$persons = Department::find($id)->persons;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question