【发布时间】:2020-07-04 11:47:13
【问题描述】:
我的表格包含下一列(price、special_price、is_special)。
+-------+------+-----------------+--------------+---------+
| id | price | special_price | is_special | qty |
+-------+-------------------------+--------------+----------+
| 1 | 100 | null | 0 | 5 |
| 2 | 120 | 99 | 1 | 0 |
| 3 | 300 | null | 0 | 1 |
| 4 | 400 | 350 | 1 | 10 |
| 5 | 75 | 69 | 1 | 0 |
| 6 | 145 | 135 | 0 | 1 |
+-------+-------+-----------------+--------------+---------+
我想获取带有条件的“价格”订购的产品,如果“is_special”列为真,则选择“special_price”列。
我想得到下一个结果。
+-------+-----------+-----------------+--------------+--------------+
| id | price | special_price | is_special | qty |
+-------+-----------------------------+--------------+--------------+
| 5 | 75 | 69 | 1 | 0 |
| 2 | 120 | 99 | 1 | 0 |
| 1 | 100 | null | 0 | 5 |
| 6 | 145 | 135 | 0 | 1 |
| 3 | 300 | null | 0 | 1 |
| 4 | 400 | 350 | 1 | 10 |
+-------+-----------+-----------------+--------------+--------------+
在原始 SQL 上看起来像
SELECT *
FROM products
ORDER BY IF(is_special=0, price, special_price ) ASC;
我使用 Laravel 并希望订购并在结果中获取查询生成器。
例如我用虚拟属性做的
/**
* Get current price
*
* @return mixed
*/
public function getCurrentPriceAttribute()
{
return $this->is_special ? $this->special_price : $this->price;
}
并排序集合$products->sortBy('current_price'),但此时我想获得查询生成器的结果。
查询生成器不适用于虚拟属性。
我正在尝试按“价格”和“数量”两列进行多重排序
$query = Product::query();
$query->orderByRaw("if(is_special=0, price, special_price) " . request('price', 'ASC'));
$query->orderBy('qty', request('qty', 'DESC'));
$query->get();
我有 2 个过滤器“数量”和“价格”。
在这个多重订购中,我想按价格订购产品,然后按“数量”订购所有产品。 qty == 0 的产品,需要排在所有 qty > 0 的产品之后。
请帮帮我。
【问题讨论】:
-
也发布您的查询...
标签: php mysql laravel eloquent laravel-query-builder