您好如何在yii 2中将原始查询返回到数组?我一直在研究这个代码,我认为它应该返回多行,但是当我尝试在视图上使用foreach时,它会说为foreach()提供了无效参数
以下是错误页面:
以下是我正在处理的代码
模型
public function Showprerequisites($trno){
// $connection = Yii::$app->GetDb();
return Yii::$app->db->CreateCommand('
SELECT * FROM
(
SELECT pre1 AS col FROM ccsubject WHERE trno = 29005 AND pre1 IS NOT NULL
UNION
SELECT pre2 AS col FROM ccsubject WHERE trno = 29005 AND pre2 IS NOT NULL
UNION
SELECT pre3 AS col FROM ccsubject WHERE trno = 29005 AND pre3 IS NOT NULL
UNION
SELECT pre4 As col FROM ccsubject WHERE trno = 29005 AND pre4 IS NOT NULL
UNION
SELECT pre5 AS col FROM ccsubject WHERE trno = 29005 AND pre5 IS NOT NULL
) T1
')->execute();
}
查看
$preq = TestController::Showprerequisites(29005);
foreach($preq as $values){
echo $values['col'];
}
答案 0 :(得分:3)
您只需使用queryAll()
代替execute()
:
return Yii::$app->db->CreateCommand('SELECT...')->queryAll();
关于execute()
:
此方法仅应用于执行非查询SQL语句,例如
INSERT
,DELETE
,UPDATE
SQL。不会返回任何结果集。
关于queryAll()
:
执行SQL语句并一次返回所有行。