Rest api: limiting fields from relations


(Gzav) #1

Hi, I could not find any way to unset fields from a relation. It is easy to do that in the resource file for the main fields but I can’t find the right syntax for the relational data. I end up getting all fields from the relation.

For example something like:

public function fields()
{
    return ['id', 'email'];
}

public function extraFields()
{
    return ['profile.age'];
}

//or &expand=profile.age

Thank you if anyone got the recipe to this.


(Gzav) #2

Ok, my example was bad because the relation that I try to display through a rest api is a one to many and not a one to one (profile.age does work). Consequently, the relation is an array for a one to many. From that array I only needed one of the field. In that case I could not use item.relation.name.

To get around that I’ve created a new relation in the left joined model by adding a ‘->select(‘name’)’ to it. Now, with that relation I only get an array of names an not an array of all the fields. Hope this can help.

here is the code:

public function getTags()
{
    return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
        ->viaTable('{{%tag_journal}}', ['journal_id' => 'id'])->select('name');
}

Now I use ‘tags’ in the list of fields in the resource file.