I've implemented one-to-many relationship between Order
and Products
.
Order has more Products - Product belongs to Order
Product.belongsTo(Order, {
as: 'order',
foreignKey: 'order_id'
})
Order.hasMany(Product, {
as: 'products',
foreignKey: 'order_id'
})
When I create new Order
with create
method, returned object doesn't include array of empty Products
.
I tried to use options for create
method like this:
const newOrder = await Order.create({ }, {
include: [{
as: 'products',
model: Product
}]
});
// products attribute in newOrder doesn't exist.
I expected object:
{
id: 1;
products: []
}
but only property id
attribute was returned in this object - without products
empty array.
Of course, if findByPk
or findAll
method with include
option is used, products are also included. But it's useless query for this usage.
How to return also products
without manual adding it to response object?
You can add products: []
to create
option. This won't execute any INSERT
query to products
table but it will be returned as is.
const newOrder = await Order.create(
{ products: [] },
{
include: [{
as: 'products',
model: Product
}]
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.