我想使用 createCommand 在 Yii 中运行准备好的查询,但以模型而不是关联数组的形式获取结果。
class Fruit extends ActiveRecord {
public function eat() {return this;};
}
// This will be an extremely complicated query so I need
// to write it raw without any kind of query builder
$rows = Yii::$app->db->createCommand('SELECT * FROM fruits WHERE color = :color')
->bindValue('color', 'blue')->queryAll();
$fruits = magicallyTurnIntoFruit($rows);
$fruits[0]->eat()->save();
如何实现这一点?
最佳答案
您可以使用 findBySql
,如官方文档所述 here 。
举个例子:
$customers = Customer::findBySql('SELECT * FROM customer')->all();
如果您需要使用QueryBuilder
创建SQL
,并在findBySql
中使用它,您可以引用this question或类似的!
关于php - 在 Yii2 中以模型而不是关联数组的形式获取命令查询结果,或将其转换为模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614116/