如何在yii2 gridview数据行中获取上一行和下一行模型ID

How to get previous and next row model ID in yii2 gridview data row

在 GridView 小部件中显示我从自定义查询中获取的 ActiveDataprovider 结果时,我想在显示记录时获取下一行和上一行 $model->id,我需要做的是显示 links 到上一个和下一个 posts 在阅读模式下,我的 gridview 已经生成 link 到 post 视图,但似乎没有获取下一个数据库行的记录 ID 的选项

我已经尝试在可用函数中使用默认值,但它们似乎没有任何相关数据

GridView::widget([
    'dataProvider' => $dataProvider,
    ...
    'columns' => [
        ...
        [
           'label'=>'Post Name',
           'format' => 'raw',
           'value'=>function ($data, $key, $index, $obj) {
                // this is what i have right now
                return Html::a($data->name, ['view', 'id' => $data->id]);

                //ideally i would like something like this
                return Html::a($data->name, ['view', 
                     'id' => $data->id,
                     'prev' => $prev->id,
                     'next' => $next->id
                ]);
            },
        ],
    ],
    ....
)];

尝试在 value callback 中传递 $dataProvider:

GridView::widget([
    'dataProvider' => $dataProvider,
    ...
    'columns' => [
        ...
        [
           'label'=>'Post Name',
           'format' => 'raw',
           'value'=>function ($data, $key, $index, $obj) use($dataProvider) {


                // Check prev and next object
                $models = $dataProvider->models;
                $prev = ($index>0) ? $models[$index-1] : null;
                $next = ($index < ((count($model)-1)) ? $models[$index+1] : null; 

                //ideally i would like something like this
                return Html::a($data->name, ['view', 
                     'id' => $data->id,
                     'prev' => ($prev != null) ? $prev->id : '',
                     'next' => ($news != null) ? $next->id : '',
                ]);
            },
        ],
    ],
    ....
)];

由于 $index 是模型的正确键,我们可以这样做。不需要在每次调用中调用 $models = $dataProvider->models; 使其更快。

$keys = $dataProvider->keys;

GridView::widget([
    'dataProvider' => $dataProvider,
    ...
    'columns' => [
        ...
        [
           'label'=>'Post Name',
           'format' => 'raw',
           'value'=>function ($data, $key, $index, $obj) use ($keys) {


                // Check prev and next object
                $prevId = ($key > 0) ? $keys[$index-1] : '';
                $nextId = ($key < ((count($keys)-1)) ? $keys[$index+1] : '';

                return Html::a($data->name, ['view',
                    'id' => $data->id,
                    'prev' => $prevId,
                    'next' => $nextId,
                ]);
            },
        ],
    ],
    ....
)];