Rest api: limiting fields from relations

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.

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.

I just add have two namespaces: common and API REST, then copy (extend) common models in api and configure fields() method.
I can add code example if someone want.

rhNs Tomasz, your solution is indeed more elegant to me.
Xav