Sequelize:急切加载和排序(在父表上)

Posted

技术标签:

【中文标题】Sequelize:急切加载和排序(在父表上)【英文标题】:Sequelize: Eager Loading and Ordering (on parent table) 【发布时间】:2016-10-14 12:34:58 【问题描述】:

我在 FeathersJS 项目中进行 Sequelize,在尝试急切加载关联和按父表排序时遇到问题。如果我只是将订单 OR 添加到查询中,一切正常,当我同时使用这两个时,我会收到错误:Unhandled rejection Error: 'sales_flat_order' in order / group clause is not valid association

查询:

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;
;

【问题讨论】:

这能回答你的问题吗? Ordering results of eager-loaded models in Node Sequelize 【参考方案1】:

问题是

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

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

sequelize.models.orders
.findAll(

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

你要找的代码可能很简单

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

按您应用findAll() 的型号排序。所以它通过orders.createdAt订购。

【讨论】:

以上是关于Sequelize:急切加载和排序(在父表上)的主要内容,如果未能解决你的问题,请参考以下文章

在父表上存储 1:N 关系中的特定列

Sequelize 急切加载错误

使用 Sequelize 在父对象中查找子对象

Sequelize 关联 hasOne,belongsTo

在使用急切加载的 findOne Sequelize 方法期间,Nodejs 堆内存不足

mysql外键说明