0

I want to run a prepared query in Yii using createCommand, but get results as models instead of associative arrays.

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();

How do accomplish this?

A. Ding
  • 3
  • 2

1 Answers1

0

You can use findBySql as official doc describes it here.

As an example:

$customers = Customer::findBySql('SELECT * FROM customer')->all();

In case you need to create your SQL using QueryBuilder, and use it in findBySql, you can refer to this question or similar!

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62