0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The pleasure is all mine. Happy Coding :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.