我正在尝试将 Sql 查询转换为 Laravel 查询。使用的Daybase是postgresql
Laravel 查询
$c_list = DB::table('cities')
->select('id as city_id', 'name as lang_name', 'ascii_name as city_name', 'iso2', DB::raw("(CASE WHEN iso2 = 'DE' THEN 'Germany' WHEN iso2 = 'CH' THEN 'Switzerland' ELSE 'India' END) AS codeCity"))
->whereIn('iso2', array('DE', 'IN', 'FR', 'TA', 'CH'))
->orderBy('codeCity','asc')
->orderBy('city_name','asc')
->get();
显示错误
SQLSTATE[42703]: Undefined column: 7 ERROR: column "codeCity" does not exist LINE 1:
Output is getting when orderby codeCity is removed
数据库架构
没有 orderby 结果正在获取
$c_list = DB::table('cities')
->select('id as city_id', 'name as lang_name', 'ascii_name as city_name', 'iso2', DB::raw("(CASE WHEN iso2 = 'DE' THEN 'Germany' WHEN iso2 = 'CH' THEN 'Switzerland' ELSE 'India' END) AS codeCity"))
->whereIn('iso2', array('DE', 'IN', 'FR', 'TA', 'CH'))
->get();
最佳答案
您可以使用selectRaw()
代替DB:raw()
:
DB::table('cities')
->select('id as city_id', 'name as lang_name', 'ascii_name as city_name', 'iso2')
->selectRaw("(CASE
WHEN iso2 = 'DE' THEN 'Germany'
WHEN iso2 = 'CH' THEN 'Switzerland'
ELSE 'India'
END)
AS codeCity")
->whereIn('iso2', array('DE', 'IN', 'FR', 'TA', 'CH'))
->orderBy('codeCity','asc')
->orderBy('city_name','asc')
->get();
编辑(用于回复):太奇怪了。但你可以尝试另一个这样的
DB::table('cities')
->select('id as city_id', 'name as lang_name', 'ascii_name as city_name', 'iso2')
->whereIn('iso2', array('DE', 'IN', 'FR', 'TA', 'CH'))
->orderByRaw("CASE
WHEN iso2 = 'DE' THEN 'Germany'
WHEN iso2 = 'CH' THEN 'Switzerland'
ELSE 'India'
END",'asc')
->orderBy('city_name','asc')
->get();
关于php - 将 SQl 转换为 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72342852/