我的查询db raw laravel是这样的:
public function getTopProduct($price = null) {
$products = DB::select(DB::raw('SELECT *
FROM (
SELECT a.*, b.name AS store_name, b.address
FROM products a
JOIN stores b ON b.id = a.store_id
WHERE a.status = 1
) AS product
GROUP BY store_id')
);
return $products;
}
我要添加条件
如果价格不为空,则在where
上添加条件价格
例如,price = 1000,那么在where
上的查询就像这样:
WHERE a.status = 1 AND a.price < 1000
如果price = null,则不执行条件AND a.price < 1000
我该怎么做?
更新
我稍微修改了一下代码流
我这样试:
public function getTopProduct($price)
{
if($price == 1)
$price_condition = 'WHERE price > 1000';
else if($price == 2)
$price_condition = 'WHERE price >= 500 AND a.price <= 1000';
else if($price == 3)
$price_condition = 'WHERE price < 500';
else
$price_condition = '';
$products = DB::select('SELECT *
FROM (
SELECT a.*, b.name AS store_name, b.address
FROM products a
JOIN stores b ON b.id = a.store_id
WHERE a.status = 1
) AS product
GROUP BY store_id
'.$price_condition
);
return $products;
}
而且很管用
你觉得如何?
我的解决方案是否正确?或者你有更好的解决方案?
3条答案
按热度按时间sbdsn5lh1#
xxhby3vn2#
您可以在查询构建器中使用高级连接子句
frebpwbc3#
在
where
条件下尝试类似下面的代码:或
$price = $request->get('price');
希望这对你有帮助!