【问题标题】:Laravel orderBy with column value errorLaravel orderBy 列值错误
【发布时间】:2018-10-24 17:56:59
【问题描述】:

我正在尝试按列值对结果进行排序,但它不起作用

$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: 选择idcommentuser_nameproduct_idratingcountry, status, pin, created_at 来自comments shop_name = 和 product_id = 按 IF(product_url = 'customer') DESC, product_url 排序 = 手动 ASC,pin desc,rating desc)

【问题讨论】:

标签: php mysql sql laravel laravel-5.5


【解决方案1】:

MySQL IF 函数接受 三个 参数。

这个表达式无效:

  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            

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多