Reputation: 880
I have model Arhive
const Archive = sequelize.define('Archive', {
date: DataTypes.STRING,
}, {});
Archive.associate = function(models) {
Archive.hasMany(models.Video, {
foreignKey: 'ArchiveId',
onDelete: 'CASCADE',
as: 'video'
});
Archive.hasMany(models.Photo, {
foreignKey: 'ArchiveId',
onDelete: 'CASCADE'
});
};
return Archive;
};
and model Video
const Video = sequelize.define('Video', {
link: DataTypes.STRING,
pick: DataTypes.STRING,
date: DataTypes.STRING,
}, {});
Video.associate = function(models) {
Video.belongsTo(models.Archive, {
foreignKey: 'ArchiveId',
onDelete: 'CASCADE',
});
// associations can be defined here
};
return Video;
I do a search
models.Archive.findAll({
raw:true,
attributes: ['id'],
include: [{// Notice `include` takes an ARRAY
model: models.Video,
as:'video',
required:true,
attributes: ['id'],
}]
})
.then(archive => console.log(archive))
.catch(console.error)
I get unexpected
[ { id: 1, 'video.id': 1 }, { id: 1, 'video.id': 2 } ]
How to get one parent object with a child nested array ?
An example of the object to get
[ { id: 1, video[id:1,id:2] } ]
Is it possible to get a similar result with Sequelize?
Upvotes: 1
Views: 2301
Reputation: 58533
All you need to do is remove raw:true
from your query.
models.Archive.findAll({
// raw: true, // <------- REMOVE THIS
attributes: ['id'],
include: [{ // Notice `include` takes an ARRAY
model: models.Video,
as: 'video',
required: true,
attributes: ['id'],
}]
})
.then(archive => console.log(archive))
.catch(console.error)
It generates this kind of output while using it for nested levels with raw:true
.
Upvotes: 2