I have four models each having hasMany relations to each other.
A hasMany B B hasMany C C hasMany D
My main model is A and I want to fetch D through A. I am querying like this to get D.
A::with('B.C.D')->get();
I am fetching D like this:
$answer = [];
foreach(A as a) {
foreach(a->B as b){
foreach(b->C as c) {
foreach(c->D as d) {
$answer[] = d;
}
}
}
}
But I want to reduce these arrays into a single statement, is it possible to do it?
CodePudding user response:
You can use pluck()
and collapse()
.
A::with('B.C.D')->get()->pluck('B.*.C.*.D.*')->collapse();
It directly gives you D's model data.
Let me know its solve your issue or not.
CodePudding user response:
You can use laravel Helpers data_get()
to get nested data easily.
Laravel has a lots of helper functions . Going through these function helps a lot.
In your case:
data_get($variable, 'a.b.c')