php - 在 Yii2 中以模型而不是关联数组的形式获取命令查询结果,或将其转换为模型

标签 php mysql activerecord yii2

我想使用 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/

相关文章:

php - kubernetes php nginx部署共享卷

mysql - 使用 MySQL 查询查找具有匹配行的 ID

ruby - ActiveRecord 和 has_one & has_many 的使用

ruby-on-rails - 覆盖 database.yml 的策略?

ruby-on-rails - 为相关数据库创建Rails下拉列表

php - 仅在 Laravel Events 中返回时间戳

php - Symfony 2 'The process has been signaled with signal 5' 在使用 wkhtmltopdf 和 knpsnappy 时

php - 如何仅使用 SQL 而不使用 PHP 对唯一数据进行排序(分组)?

c# - ASP.Net C# - 将变量传递给 MySQL 查询

php - 我这里的代码太多,想简短一点