如何在Yii2中返回查询对象?

时间:2015-08-27 16:12:19

标签: yii2

如何将yii\db\Query的所有结果作为对象从此类查询中返回?

$query = new Query;
$query->select('id, name')
      ->from('user')
      ->limit(10);
$rows = $query->all();

1 个答案:

答案 0 :(得分:2)

试试这种方式

 use yii\db\Query;

 $query = new Query;
 // compose the query
 $query->select('id, name')
    ->from('user')
    ->limit(10);
 // build and execute the query
 $rows = $query->all();

 // accessing the value 
 foreach ($rows as $row){
    echo $row['name'];
  }

通过$ row->名称进行访问;

尝试

use common\models\User;  // or you app or backend depend where you have models
$rows = User::find()->limit(10)->all();

foreach ($rows as $row){
   echo $row->nome;

}