A
A
atis //2016-12-29 14:56:16
Yii
atis //, 2016-12-29 14:56:16

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

How can such a query be made in Yii2 using Yii::$app->db->createCommand()?
Only needed for logging.
PS : This is just an example! ActiveRecord is not relevant here.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-12-29
@atis2345

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;    
}

D
Dmitry, 2016-12-29
@slo_nik

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

What exactly doesn't work for you?

K
Kholmurod Isroilov, 2021-04-25
@khalmurad

$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 question

Ask a Question

731 491 924 answers to any question