dousenjue3214 2015-08-22 12:19
浏览 57
已采纳

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

I have two tables staff with columns id, name and attendance. staff_id is used as foreign key in attendance table.

I want to display staff name in attendance gridview.

Attendance model:

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

public function getStaffName() {
          return $this->staff->name;
}

and in index.php I used this code

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

to get value of staff name. In this way I am getting staff name successfully but the problem is that when I make search for staff name in gridview it say "staff_id" should be integer as I define it as integer, but here I want to search name of staff instead of id.

How is this possible ? Thanks in advance

  • 写回答

3条回答 默认 最新

  • dshgdhdfcas30210 2015-08-22 12:43
    关注

    Add this in search model

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

    And add below code at filter query.

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

    In staff.name that in staff is table name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分