raxa raxa - 1 year ago 757
PHP Question

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

I have two tables

with columns
is used as foreign key in

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([
]); ?>

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download