Search code examples
laraveleloquenteloquent-relationship

How can I fetch the nested relation through a single statement into an array


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?


Solution

  • 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.