Laravel 查询生成器如何编写具有 CAST 和 REPLACE 函数的 orderBy 查询
Laravel query builder how to write orderBy query having CAST and REPLACE functions
我有这样的查询
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)
我会使用 DB facade 并使用原始 mysql
确保将 DB facade 添加到控制器或任何地方 运行 this
use Illuminate\Support\Facades\DB;
然后
DB::table('history_cost_estimation')->select('area')->orderBy(DB::raw('CAST(REPLACE(area, ' ', ''), 'INT')));
我有这样的查询
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)
我会使用 DB facade 并使用原始 mysql
确保将 DB facade 添加到控制器或任何地方 运行 this
use Illuminate\Support\Facades\DB;
然后
DB::table('history_cost_estimation')->select('area')->orderBy(DB::raw('CAST(REPLACE(area, ' ', ''), 'INT')));