如何在yii2中通过搜索和过滤获得外键值而不是网格视图中的关键字


How to get foreign key value instead of key in grid view with searching and filtering in yii 2?

我有两个表staff,其中有列idnameattendance。CCD_ 5被用作CCD_ 6表中的外键。

我想在考勤表中显示员工姓名。

考勤型号:

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

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

     <?= GridView::widget([
            [
             'attribute'=>'staff_id',
            'value'=>'StaffName',
            ],
]); ?>

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

这怎么可能?提前感谢

将其添加到搜索模型中

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

并在筛选器查询中添加以下代码。

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

staff.name中,staff中的是表名。

您可以使用此代码

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

或者使用此代码

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

或者在你的代码中,你可以使用这个

<?= GridView::widget([
    [
      'attribute'=>'staff_id',
      'value'=>'getStaffName()',
    ],
]); ?>

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

You can use this code
1. relation in models
 public function getCountry()
    {
        return $this->hasOne(Country::className(), ['id' => 'country_id']);
    }
2. in grid view
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii'grid'SerialColumn'],
            'id',
            'state_name',
           // 'country_id',
         [
      'attribute'=>'country_id',
      'value'=>'country.country_name',
    ],
            ['class' => 'yii'grid'ActionColumn'],
        ],
    ]); ?>
3. Search Models
   change country_id from integer to safe than change on search function
 public function search($params)
    {
        $query = State::find();
        $query->joinWith(['country']);
       $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $this->load($params);
        if (!$this->validate()) {
            return $dataProvider;
        }
        $query->andFilterWhere([
            'id' => $this->id,
        ]);
        $query->andFilterWhere(['like', 'state_name', $this->state_name])
         ->andFilterWhere(['like', 'country.country_name', $this->country_id]);
return $dataProvider;
    }