如何在yii 2中使用搜索和过滤获取外键值而不是网格视图中的键?

rax*_*axa 9 php gridview yii yii2

我有两个staff带列的表id,nameattendance.staff_id用作attendance表中的外键.

我想在出勤gridview中显示员工姓名.

出勤模式:

public function getStaff()
{
        return $this->hasOne(Staff::className(), ['id' => 'staff_id']);
}

public function getStaffName() {
          return $this->staff->name;
}
Run Code Online (Sandbox Code Playgroud)

在index.php中我使用了这段代码

     <?= GridView::widget([
            [
             'attribute'=>'staff_id',
            'value'=>'StaffName',
            ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

获得员工姓名的价值.通过这种方式,我成功获得了员工姓名但问题是,当我在gridview中搜索员工姓名时,它说"staff_id"应该是整数,因为我将其定义为整数,但在这里我想搜索员工的姓名而不是id .

这怎么可能 ?提前致谢

GAM*_*ITG 6

在搜索模型中添加此项

$query->joinWith(['staff(relation name)']);

并在过滤查询中添加以下代码.

$query->andFilterWhere(['like', 'staff.name', $this->staff_id])

staff.name那里staff是表名.


Ami*_*sen 6

您可以使用此代码

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'staff.name',
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

或使用此代码

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        [
           'attribute' => 'staff.name',
           'header' => 'Staff title'
           'value'=> 'function ($model, $key, $index, $grid){
               return $model->staff->name;
           }'
        ],
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

或者在你的代码中你可以使用它

<?= GridView::widget([
    [
      'attribute'=>'staff_id',
      'value'=>'getStaffName()',
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

并且对于搜索,您可以观看此视频搜索相关表格数据