I am not able to return selected fields from my model using ActiveDataProvider for my REST API endpoint.
Here is my controller code:
return new ActiveDataProvider([
'query' => ActivityPredecessor::find()->where(['activity_id'=>$activity_id])
]);
My ActivityPredecessor has a relation with activity table as following:
public function getCurrentActivity()
{
return $this->hasOne(Activity::className(), ['activity_id' => 'activity_id']);
}
Here is my extrafields functions:
public function extraFields() {
return ['activity'];
}
But when I return the response from my controller as JSON it does not contain related 'activity' data. It just contains fields of current model (ActivityPredecessor). For example:
{
"predecessor_id": 1,
"activity_id": 98132,
"created_at": "2020-07-14 03:17:06.04294"
}
When I print dataProvider it does contain related activity
model but when I return it as JSON then it is not included in the response.
I know I can override fields function to include it like this:
public function fields()
{
$fields=parent::fields();
array_push($fields,'activity');
return $fields;
}
But if I do that then response always includes activity
model which I don't want. I want to be able to fetch different fields based fields and expand parameters in URL like this:
http://localhost:88/predecessors?fields=predecessor_id (Get only predcessor_id in response)
http://localhost:88/predecessors?fields=predecessor_id&expand=activity (Get only predcessor_id from current model but also include related model activity
in response)
But in all the cases it returns same data whether I specify fields or expand parameters or not. In short expand and fields is not working at all.
Can anyone please tell me what I am doing wrong?
expand=currentActivity
since this is how you named the relation? Anyway if you are using Yii 2.0.36 maybe try to downgrade to previous version and see if it works then. If not, something might be going on with your custom code. – Bizley