【问题标题】:Laravel how to break where chainLaravel如何打破链
【发布时间】:2022-01-10 08:42:21
【问题描述】:

我有一个“主要”查询,我想打破它的链并将数据共享给不同的案例;

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

我想拆分它的数据,例如:

$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();

但是当我生成这段代码时, 它让它进入链,并且 $type_2 永远不会返回。因为它在 type_1 内部搜索。

这个逻辑有什么问题?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    当您多次在$products 上调用where 时,条件总是会重叠。比如执行第一行,条件为type = 1,执行第二行,条件变为 type = 1 and type = 2,执行第三行,条件为type = 1 and type = 2 and type = 3

    您可以使用cloneclone 的新实例$products,如下所示:

    $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();
    

    【讨论】:

    • 那行得通。但我也需要将 type_1 更改为 (clone $products)。
    【解决方案2】:

    您可以通过以下方法来做到这一点,它也是有效的方式。

    $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');
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2020-08-21
      • 2015-06-12
      • 2015-08-21
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多