在Yii 2中使用带有Query Builder的foreach循环

For some reason this isn't working. The error I get is "Undefined index: cu_id" for the line

$cu_id = $rows['cu_id'];

I think I'm just totally using the querybuilder wrong with the foreach loop. Any help with the proper syntax for this? Thanks!

$query = new Query;

            $query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]);


    foreach ($query as $rows) {

            $cu_id = $rows['cu_id'];

            echo"CU ID: $cu_id<br /><br />";

    }

Also I'm on the Yii 2 framework in case anyone missed that.

You query not run.

$query->all()

and then foreach records or

$query->one()

and get data from one record

$query = new Query;
$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email])
$results = $query->all();

foreach ($results as $rows) {
        $cu_id = $rows['cu_id'];
        echo"CU ID: $cu_id<br /><br />";
}

You should add all() or one() for getting the rows

$query = new Query;

   $myModels=   $query->select('cu_id')
       ->from('cu_emails')
       ->where(['creator_id' => $user_id, 'email' => $email])
       ->all();

and obtained the models in $myModels

foreach ($myModels as $rows) {

        $cu_id = $rows['cu_id'];

        echo"CU ID: $cu_id<br /><br />";

}