我有以下查询:
$results = Product::where("active", "=", true)->leftJoin(/** something **/)->leftJoin(/** something **/);
然后在视图文件中处理上述数组:
foreach($results->get() as $item)
{
// do something
}
现在,这个视图太通用了,在近 50 页之间共享。我不能以任何可能的方式改变观点。现在,我需要一种方法来更改控制器中的查询结果,我无法过滤结果,因为它get()
在视图中。我需要知道如何将MySQL的WHEN语句注入我的雄辩查询(使用Product
模型的上述查询)。
我应该怎么做?我需要这样的东西:
$results = Product::select("is_special WHEN price > 500 THEN 'true' ELSE 'false' ")->where("active", "=", true)->leftJoin(/** something **/)->leftJoin(/** something **/);
我有任何其他方法可以在get()
之前过滤结果,我欢迎!
你能先预处理一些结果吗?如
$preSelected = Product::select(/** something **/)->where(/** x **/);
和另一个控制器功能
$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
以提高安全性并减少例如.SQL注射的可能性。