Laravel循环查询范围 [英] Laravel Query Scope in Loop
问题描述
我有一个循环,该循环运行查询并构建一个关联数组,每个结果集一个键/值对.发生的情况是,范围在循环迭代时不断堆积.
I have a loop that runs a query and builds an associative array, one key/value pair for each result set. What's happening is that the scopes keep piling up as the loop iterates.
<?php
foreach ($master_asset_categories as $master_category) {
$master_assets_this_category = $asset_query->group($master_category->id)->get();
$master_asset_array[$master_category->id] =
$master_assets_this_category;
}
group()范围会不断添加到每个循环中,因此会导致类似...
The group() scope keeps adding onto each loop so it results in something like...
group($master_category->id)->group($master_category->id)->group($master_category->id)->group($master_category->id)
每个循环的$ master_category-> id不同.因为每个Asset模型只有一个asset_group_id,并且所有where子句都用"and"链接,所以该查询不返回任何内容.
With the $master_category->id being different with each loop. That makes the query return nothing since each Asset model has only one asset_group_id and all of the where clauses get chained with "and".
在每次迭代后,我可以用来删除最新的group()范围,以便在每次迭代中仅使用单个当前组($ master_category-> id)范围吗?
What can I use to remove the latest group() scope after each iteration so there is only the single current group ($master_category->id) scope used on each iteration?
推荐答案
这是因为 $ asset_query
是一个对象.代替:
This is because $asset_query
is an object. Instead of:
$master_assets_this_category = $asset_query->group($master_category->id)->get();
您应该在这里使用:
$master_assets_this_category = (clone $asset_query)->group($master_category->id)->get();
在每个查询中仅具有一个 group($ master_category-> id)
范围,而不是应用先前迭代中的多个范围.
to have in each query only single group($master_category->id)
scope instead of applying multiple scopes from previous iterations.
使用 clone
时,您将始终以与循环之前相同的对象开始.
When using clone
you will start always with the same object that you had before loop.
这篇关于Laravel循环查询范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!