Yii2 Gridview显示4个相同的结果页面

时间:2017-01-10 17:52:53

标签: gridview yii yii2 yii2-advanced-app

我正在开发基于yii2高级应用程序模板的Web应用程序。我编写了一个数据库查询,并使用findbysql()通过gii CRUD生成的网格视图返回正确的记录来实现它。但是由于某种原因,返回了4页相同的结果。每个页面按顺序显示相同的主键(1-10),而元素索引在所有4个页面(1-40)中线性增加。

我已经注释掉了动作栏,所以我认为我不需要包含CRUD .php文件

videoController.php

public function actionIndex()
{

    $sql =  'SELECT videos.idvideo, videos.filelocation, events.event_type, events.event_timestamp
                    FROM (((ispy.videos videos
                        INNER JOIN ispy.cameras cameras
                            ON (videos.cameras_idcameras = cameras.idcameras))
                        INNER JOIN ispy.host_machines host_machines
                            ON (cameras.host_machines_idhost_machines =
                                    host_machines.idhost_machines))
                        INNER JOIN ispy.events events
                            ON (events.host_machines_idhost_machines =
                                    host_machines.idhost_machines))
                        INNER JOIN ispy.staff staff
                            ON (events.staff_idreceptionist = staff.idreceptionist)
                    WHERE     (staff.idreceptionist = 182)
                            AND (events.event_type IN (23, 24))
                            AND (events.event_timestamp BETWEEN videos.start_time
                                   AND videos.end_time)'; */
        $query = Videos::findBySql($sql);

    $dataProvider = new ActiveDataProvider([
        'query' =>  $query,
    ]);

    return $this->render('index', [
        'dataProvider' => $dataProvider,
    ]);

}

视图

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'idvideo',
        'event_type',
        'event_timestamp',
        'filelocation',
        //['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

如果我需要更具体或包含任何其他信息,请告诉我。

提前致谢

2 个答案:

答案 0 :(得分:1)

问题是分页需要SQL修饰符offset,它对findBySql的结果没有影响。请参阅Yii doc

您必须在控制器中使用$ _GET [&#39; page&#39;]和$ _GET [&#39; per-page&#39;],例如:

$page = array_key_exists('page', $_GET) ? $_GET['page']-1 : 0;
$perPage = array_key_exists('per-page', $_GET) ? $_GET['per-page'] : 30;
$offset = $page * $perPage;

$sql = "SELECT ...
        OFFSET $offset LIMIT $perPage";

$dataProvider = new ActiveDataProvider([
    'query' =>  $query,
     'pagination' => [
         pageSize' => 30,
     ],
]);

答案 1 :(得分:1)

还在关联问题here的第一部分添加了此内容,并附带说明

SELECT videos.idvideo, videos.filelocation, events.event_type, events.event_timestamp
FROM ((videos videos
    INNER JOIN cameras cameras
        ON (videos.cameras_idcameras = cameras.idcameras))
    INNER JOIN events events
        ON (events.host_machines_idhost_machines =
            cameras.host_machines_idhost_machines))
WHERE (events.staff_idreceptionist = 182)
        AND (events.event_type IN (23, 24))
        AND (events.event_timestamp BETWEEN videos.start_time
               AND videos.end_time);