Say I have the following relation:
User.belongsTo(Image, { foreignKey: 'profileImage' })
Image.hasOne(User, { foreignKey: 'profileImage' })
If I call User.findOne()
, I get:
> User.findOne()
User {
...
profileImage: 1 // image_id
}
How can I instead load the image, something like this:
> User.findOne({ ... })
User {
...
profileImage: Image {
id: 1 // image_id
...
}
}
I have tried passing in options to .findOne()
using the docs here but can't get it working.
I could construct a raw join or run multiple queries, but I feel there should be a nice way to achieve this.
Thanks in advance for the help!
CodePudding user response:
You just need to use include
option like this
User.findOne({
include:[{
model: Image
}]
})
See Eager loading