问题
Hello how do I return a raw query into an array in yii 2? I have been working on this code and I assume that it should return multiple rows but when I try to a foreach on a view it it says that Invalid argument supplied for foreach()
Here is the error page:
Here is the code I am working on
Model
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();
}
View
$preq = TestController::Showprerequisites(29005);
foreach($preq as $values){
echo $values['col'];
}
回答1:
You should simply use queryAll() instead of execute() :
return Yii::$app->db->CreateCommand('SELECT...')->queryAll();
About execute() :
This method should only be used for executing non-query SQL statement, such as
INSERT
,DELETE
,UPDATE
SQLs. No result set will be returned.
About queryAll() :
Executes the SQL statement and returns ALL rows at once.
来源:https://stackoverflow.com/questions/39343269/returning-raw-query-as-array-yii-2