2017-06-22 91 views
0

我在MySQL如何在QueryBuilder中放入SQL請求並避免使用``?

SELECT * FROM pt WHERE id=98 ORDER BY FIELD (position, 4, 3, 2, 1, 5) 

這個SQL請求,我需要在Yii2查詢。當我寫

'query' => Pt::find()->where(['id' => $model->id]) 
     ->OrderBy('FIELD (`position`, 4, 3, 2, 1, 5)') 

我收到

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 20' at line 1 
The SQL being executed was: SELECT * FROM `pt` WHERE `id`=98 ORDER BY FIELD (`position`, `4`, `3`, `2`, `1`, `5)` LIMIT 20 

如何避免``的要求嗎?

+0

嘗試' - >排序依據( '字段(位置,4,3,2,1,5)')' – RiggsFolly

回答

2

使用yii\db\Expression類,因爲它可以幫助您插入RAW代碼(不會將其格式化爲生成的查詢),但要謹慎!不要在數據庫查詢中將用戶輸入作爲RAW插入,因爲它會導致嚴重的漏洞。

工作代碼看起來如下:

'query' => Pt::find()->where(['id' => $model->id]) 
     ->orderBy(new \yii\db\Expression('FIELD (`position`, 4, 3, 2, 1, 5)')) 
+0

謝謝!有用。我只用它在GridView中輸出。 – Vadim

+0

這是我的榮幸! – Yerke

相關問題