Answer the question
In order to leave comments, you need to log in
How can I use PDO::FETCH_CLASS for pure database queries in Yii2?
class User
{
public $id;
public $name;
}
$sql = "SELECT id, name FROM users";
$sth = Yii::$app->db->pdo->prepare($sql);
$sth->execute();
$sth->fetchAll(PDO::FETCH_CLASS, 'User');
Answer the question
In order to leave comments, you need to log in
use DataReader
for this purpose
For example:
class User extends \yii\base\Object
{
public $id;
public $name;
}
$query = new \yii\db\Query;
$query->select(['id', 'name'])->from('users');
$command = $query->createCommand(Yii::$app->db);
$reader = $command->query();
while ($user = $reader->readObject(User::className(), [])){
$users[] = $user;
}
Good afternoon.
Everything is described in the documentation
And more
And more
An example from the documentation:
$command = (new \yii\db\Query())
->select(['id', 'email'])
->from('user')
->where(['last_name' => 'Smith'])
->limit(10)
->createCommand();
// показать SQL запрос
echo $command->sql;
// показать привязываемые параметры
print_r($command->params);
$sql = "SELECT id, name FROM users";
$command = Yii::$app->db->createCommand($sql);
$users = $command->queryAll(\PDO::FETCH_CLASS);
/**
* или
* $users= $command->queryAll(8);
**/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question