我的查询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;
}
它有效
你觉得怎么样?
我的解决方案是否正确?或者你有更好的解决方案?
答案 0 :(得分:0)
使用where
条件尝试以下代码:
$price = array_column($request->get('price'), 'id');
或强>
$price = $request->get('price');
$query = 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'))
->when($price == 1, function($query) use ($price) {
$query->where('price', '>', '1000');
})
->when($price == 2, function($query) use ($price) {
$query->where('price', '>=', '500')
->where('a.price', '<=', '1000');
})
->when($price == 3, function($query) use ($price) {
$query->where('price', '<', '500');
})
->when($price == '', function($query) use ($price) {
$query->where('your_where_when_price_empty');
})
->get();
希望这能帮到你!
答案 1 :(得分:0)
public function getTopProduct($price = null) {
if($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')
);
}else{
$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 AND a.price='.$price.'
) AS product
GROUP BY store_id')
);
}
return $products;
}
答案 2 :(得分:0)
您可以在查询生成器
中使用Advanced Join ClausesDB::table('products')
->join('stores', function ($join) use ($price) {
$query = $join->on('stores.id', '=', 'products.store_id')
->where('products.status', '=', 1);
if (!empty($price)) {
$query->where('products.price', '<', 1000);
}
})
->select('products.*', 'stores.name AS store_name', 'stores.address')
->groupBy('products.store_id')
->get();