php - 如何在 yii2 中将 MySql Query 传递给 ActiveDataProvider

标签 php mysql yii2

我有一个带连接的 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/

相关文章:

mysql - 并发请求时 Hikari CP 连接错误

Yii2:从 '$this->goBack()' 排除特定的 Controller Action

php - jQuery.AJAX post() - 一些疑问和问题

php - 在关联(数组)上找到 Doctrine\Common\Collections\ArrayCollection 类型的实体,但期待(其他)

php - mySQL 从多个外键返回字段名称

php - 条件 LEFT JOIN MYSQL PHP

mysql - 按年份排列的比赛日期

php - Yii2 基本背景变化

php - ccavenue 支付网关错误,如 10002

php - 保持 select from wordpress 循环的值