Paresh Maheshwari
Paresh Maheshwari

Reputation: 189

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?

Upvotes: 0

Views: 779

Answers (2)

Bishal Jung Chettri
Bishal Jung Chettri

Reputation: 384

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')

Upvotes: 0

Vivek Pawar
Vivek Pawar

Reputation: 704

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.

Upvotes: 1

Related Questions