EntityQuery PHP issue when assigning the query to a variable I am very confused about this behavior of EntityQuery, or maybe I am just missing something basic about PHP.
Here is the query I am working with:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  -&gt;condition($entity_type-&gt;getKey('bundle'), $entity_type_bundle)
  -&gt;condition($entity_type-&gt;getKey('uid'), $uid)
  -&gt;condition('field_int_points', 1, '=');
return $entity_query_points1;

This is fine.
But if this query returns no results, I wanted to immediately execute another query.  So I made a switch statement and wrote code like this:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  -&gt;condition($entity_type-&gt;getKey('bundle'), $entity_type_bundle)
  -&gt;condition($entity_type-&gt;getKey('uid'), $uid)
  -&gt;condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query-&gt;count()-&gt;execute();
if ($count &gt;= 1) {
  return $entity_query_points1;
}

This fails with a WSOD (I am using this code with the JSON:API Resources module):
TypeError: Argument 2 passed to Drupal\jsonapi_resources\Resource\EntityQueryResourceBase::loadResourceObjectsByEntityIds() must be of the type array, string given, called in /app/web/modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php on line 97 in Drupal\jsonapi_resources\Resource\EntityQueryResourceBase-&gt;loadResourceObjectsByEntityIds() (line 125 of modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php).

If I use the following code, it works (query resolved correctly, no WSOD):
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  -&gt;condition($entity_type-&gt;getKey('bundle'), $entity_type_bundle)
  -&gt;condition($entity_type-&gt;getKey('uid'), $uid)
  -&gt;condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query-&gt;count()-&gt;execute();
if ($count &gt;= 1) {
  $entity_query_score1 = \Drupal::entityQuery($entity_type_id)
    -&gt;condition($entity_type-&gt;getKey('bundle'), $entity_type_bundle)
    -&gt;condition($entity_type-&gt;getKey('uid'), $uid)
    -&gt;condition('field_int_points', 1, '=');
  return $entity_query_points1;
}

But... why?  I executed the count on $entity_query, but I have to redefine $entity_query_score1 to return the query as expected.  I know having to redefine the query means I have screwed up somehow, but I don't know what my mistake is.
Objects work differently than regular variables in PHP. They are &quot;assigned by reference&quot;, generally speaking. The Objects and References page in the PHP manual goes into some detail about this. Basically, your = is not working as you expect. $entity_query and $entity_query_points1 are &quot;the same object&quot;.
As noted by @baikho in the comments, you'll need to use clone to achieve what you're trying to do.
$entity_query = clone $entity_query_points1;