Laravel查询生成器如何编写排序依据为CAST查询和替换功能
问题描述:
我有这样Laravel查询生成器如何编写排序依据为CAST查询和替换功能
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外观和使用原始的MySQL
确保数据库门面添加到控制器或任何你正在运行此
use Illuminate\Support\Facades\DB;
然后做
DB::table('history_cost_estimation')->select('area')->orderBy(DB::raw('CAST(REPLACE(area, ' ', ''), 'INT')));