Using include with attributes in Sequelize is a powerful feature that allows you to query an associated model along with its related models and specify the exact attributes to retrieve. This effectively reduces data redundancy and improves query efficiency.
For example, suppose we have two models: User and Post, where User represents users and Post represents their posts, with a one-to-many relationship between them.
First, we need to define this relationship in the model definitions:
javascriptUser.hasMany(Post, { foreignKey: 'userId' }); Post.belongsTo(User, { foreignKey: 'userId' });
If we want to query all users and retrieve only the title and createdAt attributes of their posts, we can use the include option in the findAll method:
javascriptconst users = await User.findAll({ include: [{ model: Post, attributes: ['title', 'createdAt'] }] });
In this query, the include array instructs Sequelize to include the Post model. The attributes option specifies the fields of interest, so the returned data includes a posts array for each user object, with each element containing only the title and createdAt fields.
This query is particularly useful because it provides precise control over the data returned, avoiding unnecessary redundancy, which is critical when handling large datasets and relationship-heavy applications.
Additionally, if you need to filter or sort the posts, you can use where or order options within include:
javascriptconst users = await User.findAll({ include: [{ model: Post, attributes: ['title', 'createdAt'], where: { status: 'active' }, order: [ ['createdAt', 'DESC'] ] }] });
In this example, we add filtering to include only active posts and sort them by creation time in descending order. This demonstrates the versatility and power of include, making data queries more flexible and robust.