Skip to content

Filter fields retrieved by eager? #1074

@mike-kelly

Description

@mike-kelly

I have Card, Tag and Project models.
Tag has a ManyToMany relationship with Card, Card has a ManyToMany relationship with Tag and Project.

I want to retrieve tags which are related to cards which in turn are related to a single project.
So I did this:

Tag
      .query()
      .eager('cards')
      .joinRelation('[cards.[projects]]')
      .where('cards:projects.id', req.query.projectId)
      .groupBy('tags.id')
      .then((tags) => {
        res.json(tags);
      })
      .catch((error) => {
        console.log(error);
        res.send('An error occured');
      });

However I don't want to retrieve all the Cards' properties, only the card id. So I added a filter to my Tag Model's relationMapping:

class Tag extends BaseModel {

  static get tableName() {
    return 'tags';
  }

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['title'],

      properties: {
        id: {type: 'integer'},
        color: {type: 'string', minLength: 4, maxLength: 7},
        bgColor: {type: 'string', minLength: 4, maxLength: 7},
        tCreated: {type: 'string'},
        tModified: {type: 'string'}
      }
    };
  }

  static get relationMappings() {
    const Card = require('./card');

    return {
      cards: {
        relation: BaseModel.ManyToManyRelation,
        modelClass: Card,
        filter: query => query.select('cards.id'),
        join: {
          from: 'tags.id',
          through: {
            from: 'cards_tags.tag_id',
            to: 'cards_tags.card_id'
          },
          to: 'cards.id'
        }
      }
    };
  };
}

However, the query I displayed returns all properties of Card. If I change the filter to filter: query => query.select('id'), I get an error about id being ambiguous.

How can I limit eager('cards') so that it just returns card.id for each card?

(It would also be useful to include a field cardCount with each tag result, but I couldn't manage that in the same query - is that possible?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions