我有一个带连接的 mysql 查询,它运行良好。我想将结果传递给 Yii2 ActiveDataProvider。 我的 Controller 代码看起来像
`
public function actionIndex()
{
$theme = Theme::find();
$query = "SELECT t.*,COUNT(d.id) AS total_downloads FROM `themes` AS T
LEFT JOIN downloads AS D
ON D.theme_id = T.id GROUP
by t.id ORDER BY total_downloads DESC LIMIT 6";
$connection=Yii::$app->db;
$trends = $connection->createCommand($query);
$model = $trends->queryAll();
$object = (object) $model;
$ActiveDataProvider = new ActiveDataProvider(['query' => $object]);
return $this->render('trendings',[
'ActiveDataProvider'=>$ActiveDataProvider,
]);
}`
和查看文件代码`
ListView::widget([
'dataProvider' => $ActiveDataProvider,
'options' => [
'tag' => 'div',
'class' => 'list-wrapper',
'id' => 'list-wrapper',
],
'pager' => [
'firstPageLabel' => 'first',
'lastPageLabel' => 'last',
'prevPageLabel' => '<span class="glyphicon glyphicon-chevron-left"></span>',
'nextPageLabel' => '<span class="glyphicon glyphicon-chevron-right"></span>',
'maxButtonCount' => 3,
],
// 'layout' => "{pager}\n{items}\n{summary}",
'summary' => false,
'itemView' => '_list',
]);
?>`
因为我已经通过了 QueryAll,所以 ActiveDataProvider 没有唤醒并传递错误““查询”属性必须是实现 QueryInterface 的类的实例,例如 yii\db\Query 或其子类”
最佳答案
你没有传递queryAll()
,你传递了一个函数queryAll()
的结果,它是一个对象数组。确保不要使用它:
$theme = Theme::find();
改变这个:
$query = "SELECT t.*,COUNT(d.id) AS total_downloads FROM `themes` AS T
LEFT JOIN downloads AS D
ON D.theme_id = T.id GROUP
by t.id ORDER BY total_downloads DESC LIMIT 6";
到:
$theme->select = 'YOUR SELECT HERE';
不要使用queryAll()
,只需将$theme
对象作为query
参数传递给ActiveDataProvider
。
并删除这个:
$connection=Yii::$app->db;
$trends = $connection->createCommand($query);
$model = $trends->queryAll();
$object = (object) $model;
关于php - 如何在 yii2 中将 MySql Query 传递给 ActiveDataProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887726/