php - Laravel orderBy 列值错误
问题描述
我正在尝试按列值对结果进行排序,但它不起作用
$users = Comment::select([
'id',
'comment',
'user_name',
'product_id',
'rating',
'country',
'status',
'pin',
'created_at',
])->where('shop_name',$shop)->where('product_id', $id)->with('images')->orderByRaw("IF(product_url = 'customer') DESC")->orderByRaw("product_url = manually ASC")->orderBy('pin', 'desc')->orderBy('rating', 'desc')->with('pages')->get();
我添加了这段代码
->orderByRaw("IF(product_url = 'customer') DESC")
我得到这个错误
“SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在 ') DESC、product_url = 手动 ASC、
pin
desc、rating
desc' 在第 1 行(SQL:selectid
,comment
,user_name
,product_id
,rating
,country
,status
,pin
,created_at
fromcomments
whereshop_name
= andproduct_id
= order by IF(product_url = 'customer') DESC, product_url = manual ASC,pin
desc,rating
desc)
解决方案
MySQLIF
函数接受三个参数。
此表达式无效:
IF(product_url = 'customer')
因为只有一个参数提供给IF()
函数。
我们可以这样做:
IF(product_url = 'customer',1,0)
这相当于更符合 ANSI 标准
CASE WHEN product_url = 'customer' THEN 1 ELSE 0 END
MySQL速记也可以
ORDER BY product_url = 'customer' DESC
这相当于
ORDER BY CASE
WHEN product_url = 'customer' THEN 1
WHEN product_url IS NOT NULL THEN 0
ELSE NULL
END DESC