Yii1 相当于 Sql 查询

Yii1 equivalent of the Sql query

我有这个 sql 查询

SELECT * FROM form_fields 
WHERE id NOT IN ("3", "1", "6") 
ORDER BY FIELD (id, "3" ,"1" ,"6")

我想将其转换为 yii1 查询。所以我试过这样

$SQL="SELECT * FROM form_fields WHERE id NOT IN {$sorted_array}  ORDER BY FIELD (id, $sorted_array)";
$connection=Yii::app()->db; 
$command=$connection->createCommand($SQL);
$rowCount=$command->execute(); 
$dataReader=$command->query(); 

其中 $sorted_array 的值为 Array ( [0] => 3 [1] => 1 [2] => 6 )

它给了我一个错误

PHP notice

Array to string conversion

然后我将 $sorted_array 转换为这样的字符串

$string = implode(' ', $sorted_array);

并再次执行查询

$SQL="SELECT * FROM form_fields WHERE id NOT IN {$string}  ORDER BY FIELD (id, $string)";
$connection=Yii::app()->db; 
$command=$connection->createCommand($SQL);
$rowCount=$command->execute(); 
$dataReader=$command->query(); 

现在我收到另一个错误

CDbException

CDbCommand failed to execute the SQL statement: 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 '3 1 6 ORDER BY FIELD (id, 3 1 6)' at line 1. The SQL statement executed was: SELECT * FROM form_fields WHERE id NOT IN 3 1 6 ORDER BY FIELD (id, 3 1 6)

而不是这个

SELECT * FROM form_fields 
    WHERE id NOT IN ("3", "1", "6") 
    ORDER BY FIELD (id, "3" ,"1" ,"6")

我的 yii1 查询产生了这个错误的 sql 查询

SELECT * FROM form_fields
WHERE id NOT IN 3 1 6 ORDER BY FIELD (id, 3 1 6)

如有任何帮助,我们将不胜感激

implode的第一个参数应该是逗号:

$string = implode(',', $sorted_array);

更好的方法是使用 QueryBuilder。看起来像

$result = Yii::app()->db->createCommand()
              ->select('field1, field2')
              ->from('table t')
              ->join('table2 t2', 't2.t_id = t.id')
              ->where('t.property = :property', [':property' => 1])
              ->queryRow();

它更有用,因为 QueryBuilder 使用 PDO-statements 作为参数,并根据您的 DBMS 类型使用 SQL 方言进行正确查询。

它也支持数组语句,像这样:

->where(['in', 'field', [1,2,3]])

结果是:

... WHERE field IN (1, 2, 3) ...

是的,它仍然是 DAO,没有 ActiveRecord :)