如何在Eloquent中写出WHEN THEN语句,或者在get()之前过滤结果?

时间:2014-11-17 13:17:46

标签: php laravel eloquent

我有以下查询:

$results = Product::where("active", "=", true)->leftJoin(/** something **/)->leftJoin(/** something **/);

然后在视图文件中处理上述数组:

foreach($results->get() as $item)
{
  // do something
}

现在,这个视图过于通用,在近50页之间共享。我无法以任何可能的方式改变视图。现在,我需要一种方法来更改控制器中的查询结果,我无法过滤结果,因为它在视图中是get()。我需要知道如何将WHEN语句注入我的Eloquent查询(使用Product模型进行上述查询)。

我该怎么做?我需要这样的东西:

$results = Product::select("is_special WHEN price > 500 THEN 'true' ELSE 'false' ")->where("active", "=", true)->leftJoin(/** something **/)->leftJoin(/** something **/);

我有任何其他方法可以在get()之前过滤结果,我很欢迎!

1 个答案:

答案 0 :(得分:0)

您之前可以预先处理一些结果吗?如

$preSelected = Product::select(/** something **/)->where(/** x **/);

和另一个Controller函数

$preSelected = Product::select(/** something else **/)->where(/** y **/);

然后它会是相同的

$results = $preSelected->where("active", "=", true)
             ->leftJoin(/** something **/)->leftJoin(/** something **/);

或者另一种选择是使用DB :: raw

$results = Product::select(DB::raw('is_special WHEN price > 500 THEN true ELSE false'))
             ->where("active", "=", true)->leftJoin(/** something **/)
             ->leftJoin(/** something **/);

虽然我尽量避免DB::raw以提高安全性并降低例如{1}}的可能性。 SQL注入。