P
P
Pavel Rozhkov2020-10-14 00:41:18
Laravel
Pavel Rozhkov, 2020-10-14 00:41:18

How to limit fetch depth in Laravel?

Good day colleagues, tell me how in Laravel 7 you can limit the selection of a tree structure, the essence of the idea is that users simply register under each other like in affiliate programs. I took recursive output as a basis.
In my model

public function children()
    {
        return $this->hasMany(User::class);
    }
    public function childrenRef(){
        return $this->hasMany(User::class)->with('children');
    }


and in the controller i just call
$users = User::where('user_id', 1)->with('childrenRef')->get();


The user variable receives an array of users nested into each other,
for example:
us1
--us2
--us3
------us4
----------us5
--us7
It turns out 4 nesting levels
And for example, I need to get only 3
Found 1 way this is in the template in the blade foreach has a condition
@if ($loop->depth >= 3)
      @break
@else

But the disadvantage of this solution is obvious, since a ready-made array is transferred to the template, and when there are 5-10k users in total, they will amount to 15 levels, then it is still tolerable for a request to the database
. And if there are more than 30k users, then how long will the request to the database be processed, which to pull it all out.
Based on the whole question, is it possible to somehow limit the depth of nesting, at the time of requesting a selection from the database.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question