Yii2: linked model data in Gridview
I have two models, MedicineRequestEntry and MedicineRequest. MedicineRequestEntry refers to MedicineRequest via
public function getMedicineRequests()
{
return $this->hasMany(MedicineRequest::className(),
['medicine_request_entry_id' => 'id']);
}
Now in the grid-view of MedicineReuestEntry I am trying to pull data from MedicineRequest Model using relation using two alternative ways.
as
[
'attribute' => 'is_delivered',
'value'=> 'medicineRequests.is_delivered'
],
In this method I get the value as not given. and another method:
[
'attribute' => 'is_delivered',
'value'=> '$data->medicineRequests->is_delivered'
],
In this method, I am getting an error like:
Getting an unknown property: app \ models \ MedicineRequestEntry :: $ data-> medicineRequests-> is_delivered
Now I need help what I am doing wrong here. Thank.
+3
source to share
1 answer
You have to use a callback function, see the manual :
[
'value' => function ($data) {
$str = '';
foreach($data->medicineRequests as $request) {
$str .= $request->is_delivered.',';
}
return $str;
},
],
Or for the first result of an array:
[
'value' => function ($data) {
return $data->medicineRequests[0]->is_delivered;
},
],
+3
source to share