Home  >  Article  >  Backend Development  >  Questions about laravel5.2 take

Questions about laravel5.2 take

WBOY
WBOYOriginal
2016-08-04 09:20:061547browse

<code>$room=\App\Model\Room::with(['items'=>function($query){
                $query->take(12);  
            }])->get();</code>

In the above code, the items under each room are empty. When $query->take(12); is commented out, the items appear again. Why?

Reply content:

<code>$room=\App\Model\Room::with(['items'=>function($query){
                $query->take(12);  
            }])->get();</code>

In the above code, the items under each room are empty. When $query->take(12); is commented out, the items appear again. Why?

Well...the reason is actually very simple. You can add dd() to see the SQL it generates:

<code class="php">$room = \App\Model\Room::with(['items' => function($query){
    dd($query->take(12)->toSql());  
}])->get();</code>

The following SQL will be generated (? The number represents how many of your Room there are):

<code class="sql">select * from `machines` where `machines`.`series_id` in (?, ?, ?) limit 12</code>

You can see that when you add restrictions such as take and limit, it does not limit each transaction, but limits all the associated data obtained. Therefore, when you set a very small amount, it will Part of the Room does not have Item. You can set this number to a large value, such as 100000, and you will find that items has data, because your limit is greater than the amount of data.

As for how to limit the associated data of each transaction, I found some information but there is no simple way to achieve it. The most reliable one currently is this:

Tweaking Eloquent relations – how to get N related models per parent ?

I don’t understand what it means $room=AppModelRoom::with('items')->take(12);

Obviously, there was no match.

All with is implemented through the associated model abstract public function addEagerConstraints(array $models) method.

You will find that the reason is that the data provided by the query of the associated data table in with does not match the model data you obtained, resulting in no results for the query.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn