【问题标题】:Laravel query builder how to write orderBy query having CAST and REPLACE functionsLaravel 查询构建器如何编写具有 CAST 和 REPLACE 函数的 orderBy 查询
【发布时间】:2017-10-09 19:17:14
【问题描述】:

我有这样的查询

SELECT area FROM history_cost_estimation ORDER BY CAST(REPLACE(area, ' ', '') AS INT)

我正在尝试将此类查询转换为 laravel 查询生成器,但我遇到了很多错误

这是我的尝试

App\Models\HistoryCostEstimation::orderBy("CAST(REPLACE(area, ' ', '') AS INT)",'asc')->count();

这里是错误示例

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as `)` asc' at line 1 (SQL: select count(*) as aggregate from `engineertec`.`history_cost_estimation` order by `CAST(REPLACE(area,` as `)` asc)

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-eloquent laravel-query-builder


    【解决方案1】:

    我会使用 DB 外观并使用原始 mysql

    确保将 DB 外观添加到控制器或运行它的任何地方

    use Illuminate\Support\Facades\DB;
    

    然后做

    DB::table('history_cost_estimation')->select('area')->orderBy(DB::raw('CAST(REPLACE(area, ' ', ''), 'INT')));
    

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 1970-01-01
      • 2022-11-12
      • 2016-05-02
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多