gpt4 book ai didi

javascript - Sequelize : Eager Loading and Ordering (on parent table)

转载 作者:行者123 更新时间:2023-11-29 20:53:47 25 4
gpt4 key购买 nike

我正在 FeathersJS 中 Sequelize 项目,并且在尝试急切加载关联并按父表排序时遇到问题。如果我只是将订单添加到查询中,一切正常,当我同时使用两者时,我会收到错误:未处理的拒绝错误:订单/组子句中的'sales_flat_order'是无效关联

查询:

sequelize.models.orders
.findAll({
limit: 10,
include: [ sequelize.models.items ],
order: [[ sequelize.models.orders, 'createdAt' ]],
})
.then(orders => {
// Error
});

订购型号:

const Sequelize = require('sequelize');

module.exports = function(sequelize) {
const order = sequelize.define('orders', {
id: { type: Sequelize.INTEGER, primaryKey: true, field: 'entity_id' },
customerEmail: { type: Sequelize.STRING, field: 'customer_email' },
customerFirstName: { type: Sequelize.STRING, field: 'customer_firstname' },
customerLastName: { type: Sequelize.STRING, field: 'customer_lastname' },
state: { type: Sequelize.STRING },
grandTotal: { type: Sequelize.FLOAT, field: 'grand_total' },
createdAt: { type: Sequelize.DATE, field: 'created_at' },
updatedAt: { type: Sequelize.DATE, field: 'updated_at' },
}, {
freezeTableName: true,
tableName: 'sales_flat_order',
classMethods: {
associate(models) {
order.hasMany(models.items, { foreignKey: 'orderId' });
}
}
});

return order;
};

商品型号:

const Sequelize = require('sequelize');

module.exports = function(sequelize) {
const item = sequelize.define('items', {
id: { type: Sequelize.INTEGER, primaryKey: true, field: 'item_id' },
orderId: { type: Sequelize.INTEGER, field: 'order_id' },
productId: { type: Sequelize.INTEGER, field: 'product_id' },
productType: { type: Sequelize.STRING, field: 'product_type' },
sku: { type: Sequelize.STRING },
name: { type: Sequelize.STRING },
qtyOrdered: { type: Sequelize.INTEGER, field: 'qty_ordered' },
price: { type: Sequelize.FLOAT },
createdAt: { type: Sequelize.DATE, field: 'created_at' },
updatedAt: { type: Sequelize.DATE, field: 'updated_at' },
}, {
freezeTableName: true,
tableName: 'sales_flat_order_item',
classMethods: {
associate(models) {
item.belongsTo(models.orders, { foreignKey: 'orderId' });
}
}
});

return item;
};

最佳答案

问题在于

order: [[ sequelize.models.orders, 'createdAt' ]]

尝试按关联模型sequelize.models.orders的“createdAt”列进行排序。既然你写了

sequelize.models.orders
.findAll({

并尝试按关联模型sequelize.models.orders进行排序,您尝试将模型本身作为关联引用。这不起作用,因为您创建了订单和项目之间的关联,但没有创建订单和订单之间的关联。

您正在寻找的代码可能很简单

order: [['createdAt', 'ASC' ]]

按您应用 findAll() 的模型排序。因此它通过 orders.createdAt 进行排序。

关于javascript - Sequelize : Eager Loading and Ordering (on parent table),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com