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

Php 如何在yii 2中通过搜索和过滤获得外键值而不是网格视图中的键?,php,gridview,yii,yii2,Php,Gridview,Yii,Yii2,我有两个表staff,其中包含id、name和考勤员工id用作考勤表中的外键 我想在考勤网格视图中显示员工姓名 出席人数型号: public function getStaff() { return $this->hasOne(Staff::className(), ['id' => 'staff_id']); } public function getStaffName() { return $this->staff->name;

我有两个表
staff
,其中包含
id
name
考勤
<代码>员工id用作
考勤
表中的外键

我想在考勤网格视图中显示员工姓名

出席人数型号:

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',
            ],
]); ?>

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


这怎么可能?提前感谢

将此添加到搜索模型中

$query->joinWith(['staff(relationship name)')

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

$query->andFilterWhere(['like','staff.name',$this->staff\u 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([
    '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()',
    ],
]); ?>

对于搜索,您可以观看此视频

,您可以使用此代码
1.模型中的关系
公共职能(国家)
{
返回$this->hasOne(Country::className(),['id'=>'Country\u id']);
}
2.在网格视图中
3.搜索模型
将国家/地区id从整数更改为安全值,而不是更改搜索函数
公共函数搜索($params)
{
$query=State::find();
$query->joinWith(['country']);
$dataProvider=新的ActiveDataProvider([
'query'=>$query,
]);
$this->load($params);
如果(!$this->validate()){
返回$dataProvider;
}
$query->andFilterWhere([
'id'=>this->id,
]);
$query->andFilterWhere(['like','state\u name',$this->state\u name])
->andFilterWhere(['like','country.country\u name',$this->country\u id]);
返回$dataProvider;
}

如果您定义了它们之间的关系,只需说明关系的名称,而不是列名称Thank的问题已解决。对于搜索上面的视频是相当不错的。我怎么做,如果表A没有外键表B?因为我的表使用MyISAM引擎。但是表A实际上有一列包含表B的id。Thanks@Blackjack您只需使用
$this->hasOne()
$this->hasMany()
在模型中创建函数即可。类似于
公共函数getStaff(){return$this->hasOne(Staff::className(),['id'=>'Staff\u id']);}