0

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;
}

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)

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".

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?

1 Answer 1

2

This is because $asset_query is an object. Instead of:

$master_assets_this_category = $asset_query->group($master_category->id)->get();

you should use here:

$master_assets_this_category = (clone $asset_query)->group($master_category->id)->get();

to have in each query only single group($master_category->id) scope instead of applying multiple scopes from previous iterations.

When using clone you will start always with the same object that you had before loop.

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

1 Comment

I had a feeling something like that existed - I tried several ways of getting that same effect but none of them worked. (clone) does work! That's why I come here to ask...

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.