Home > Back-end >  Laravel how to break where chain
Laravel how to break where chain

Time:12-04

I have one "main" query, and I want to break It's chain and share data to the different cases;

$products = Product::where('is_active', 1)->where('date', '>', $blabla);

I want to split It's data like:

$type_1 = $products->where('type', 1)->groupBy('x')->orderBy('x')->get();
$type_2 = $products->where('type', 2)->groupBy('x')->orderBy('x')->get();
$type_3 = $products->where('type', 3)->groupBy('x')->orderBy('x')->get();

But when I generate this code, It let It to the chain, and $type_2 never returns. Because It searches inside type_1.

What's wrong with that logic?

CodePudding user response:

When you call where on $products multiple times, the conditions will always overlap. For example, when you execute the first line, the condition is type = 1, and when you execute the second line, the condition becomes type = 1 and type = 2, when you execute the third line, the condition is type = 1 and type = 2 and type = 3.

You can use clone to clone a new instance of $products, like this:

$type_1 = $products->where('type', 1)->groupBy('x')->orderBy('x')->get();
$type_2 = (clone $products)->where('type', 2)->groupBy('x')->orderBy('x')->get();
$type_3 = (clone $products)->where('type', 3)->groupBy('x')->orderBy('x')->get();

CodePudding user response:

You can do that by following approch, Its efficient way as well.

$products = Product::where('is_active', 1)->where('date', '>', $blabla)->get();

$type_1 = $products->where('type', 1)->groupBy('x')->sortBy('x');
$type_2 = $products->where('type', 2)->groupBy('x')->sortBy('x');
$type_3 = $products->where('type', 3)->groupBy('x')->sortBy('x');
  • Related