【问题标题】:How to pass MySql Query to ActiveDataProvider in yii2如何在 yii2 中将 MySql Query 传递给 ActiveDataProvider
【发布时间】:2017-05-10 17:05:00
【问题描述】:

我有一个带有连接的 mysql 查询,它运行良好。我想将结果传递给 Yii2 ActiveDataProvider。 我的控制器代码看起来像

`

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 或其子类”

【问题讨论】:

    标签: php mysql yii2


    【解决方案1】:

    你没有传递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;
    

    【讨论】:

    • 很抱歉我忘了提。我没有使用 $theme = Theme::find();然而 。我被困在下面的代码上。
    • 这就是为什么我告诉你你应该做什么。
    • 如您所见,我使用了联接,所以我想使用自定义 sql 查询。
    • 不,你仍然不想使用自定义 sql 查询。而不是使用$theme-&gt;joinWith('relationName');如果你不使用它,使用它的目的是什么?
    • queryAll() 有什么问题?不要使用 queryAll(),只需将 $theme 对象作为查询参数传递给 ActiveDataProvider。
    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2020-09-16
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多