I have the $persons
collection that contains array of $person
eloquent object models with relations. person has many accounts and accounts has one en.
for example if want to access e1 propertie of en the way is : $person->accounts[0]->en
How can I turn $person
cascading sequence :
person=>{
p1,
p2,
accounts{
a1,
a2,
en{
e1,
e2
}
}
}
into something like:
en{
e1,
e2,
accounts{
a1,
a2
},
person{
p1,
p2
}
}
after change i want something like this $en->accounts->person->p1
You can create a relation in En model specifying the relation with Account model.
public function account(){
return $this->belongsTo(Account::class);
}
And in Account model, create a relation with Person model.
public function person(){
return $this->belongsTo(Person::class);
}
Then you will be able to retrieve the data as you asked like
//en should have account and account should be associated with person
$en->accounts->person->get();