How do I return only selected fields from the model and its relation

Actually, you can retrieve images by using withRelated, but .columns() seems to have no effect here on the morph relationship. As it returns all of the columns in any case.

withRelated: {
        images: qb => { //includes images relations
          qb.columns('url'); //doesn't return only URL. returns all fields..
        },
      }

Also, you could filter images and get the desired URL by using only lodash functions. By adding .then() after .fetchAll()

let entities = await strapi.query('articles').model.fetchAll({
      columns: ['id', 'title', 'body'],
      withRelated: ['images'],
    }).then(data => {
      let output = data.toJSON();
      output = _.map(output, (item) => {
        item.imageUrl = _.get(item, ['images', 'formats', 'thumbnail', 'url']);
        delete item.images;
        return item;
      });
      return output;
    });

Result:

[
    {
        "id": 1,
        "title": "fweq",
        "body": "fwqef"
    },
    {
        "id": 2,
        "title": "fewqf",
        "body": "fqwf",
        "imageUrl": "/uploads/thumbnail_photo_2020_03_29_16_28_23_3_bcf552acd3.jpg"
    },
    {
        "id": 3,
        "title": "fwqefqwe",
        "body": "fw"
    }
]
1 Like