Included models are failing to properly inject attributes for virtual fields
See original GitHub issueWhat are you doing?
I have defined a model, Image
, with the virtual field url
. This virtual field is dependent on another attribute, path
.
path: Sequelize.STRING,
url: {
type: Sequelize.VIRTUAL(Sequelize.STRING, ['path']),
get: function() {
if (this.getDataValue('path')) {
return `${process.env.IMAGE_ROOT}/${this.getDataValue('path')}`;
} else {
return null;
}
},
},
This model is associated with the User model. I have a User w/ id 1, and an Image belonging to that user (also w/ id 1). This image has a path, 'my-path'
.
If I look up the image by id, everything works as expected:
// image.path === `${process.env.IMAGE_ROOT}/my-path`
const image = await Image.findByPk(1, { attributes: ['id', 'url'] })
However, if we look up the image by including on the user, image.path is null:
// user.image.path === null; should === `${process.env.IMAGE_ROOT}/my-path`
const user = await User.findByPk(1, {
attributes: ['id'],
include: { model: Image, attributes: ['id', 'url']}
})
I can confirm Sequelize is generating the proper DB query, but isn’t assigning the path
attribute on the retrieved image instance when it’s included, preventing us from generating the appropriate (virtual field) url
in the getter.
I was able to solve this issue with the following modification, but am not familiar enough with the codebase to know if this is appropriate: https://github.com/redivis/sequelize/commit/d4ad97d33819ee1d6110909c761de98cd52be73f
Environment
Dialect:
- postgres Database version: 11.x Sequelize version: 5.x Node Version: 12.x Tested with latest release:
- No
- Yes, specify that version:
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:8 (3 by maintainers)
Note: I have started investigating this. Hopefully I will have time to complete it soon.
@papb @stevelacy @thieman https://github.com/sequelize/sequelize/pull/11713
I don’t have the bandwidth to update the tests, if anyone else wants to tackle…