如何 return 来自已加入 table 的值在与主 table 相同级别的续集中

how to return values from joined tables in sequelize at the same level as master table

我正在尝试找到一种方法,如何将所有连接的 table 与我的主人 table 置于同一级别...到目前为止,它只会在我的最终结果中产生嵌套值对象 ..

这是我的

Orders.findAll({
   include: [
      {model: Products, attributes: ['product_name']}
   ],
   attributes: ['id_order', 'dtime_order', 'amount']
})

我得到的是:

[
 {
   id_order: 1, 
   dtime_order: '2021-05-24T22:00:00.000Z',
   amount: 20,
   products: {
      product_name: 'Picture'
   }
 }
]

但我想得到的是:

[
 {
   id_order: 1, 
   dtime_order: '2021-05-24T22:00:00.000Z',
   amount: 20,
   product_name: 'Picture'
 }
]

我试过了 但不幸的是当我这样做的时候:

Orders.findAll({
   include: [
      {model: Products, attributes: []}
   ],
   attributes: ['id_order', 'dtime_order', 'amount', ['products.product_name', 'product_name']]
})

不适合我说

column "products.product_name" does not exist

在响应中发送回对象之前,可能有一种修改对象的 hacky 方法..但我宁愿在 Sequelize 中进行修改..

非常欢迎任何想法...谢谢你们!

编辑:添加生成的 SQL

Executing (default): SELECT "orders"."id_order", "orders"."dtime_order", "orders"."amount", "products.product_name", FROM "orders" AS "orders" LEFT OUTER JOIN "products" AS "products" ON "orders"."id_order" = "products"."ir_order";
error:   Get dashboard data error: column "products.product_name" does not exist

解决方案:

我不得不在我的协会中使用别名

Orders.hasOne(Products, {as: 'products', ....})

然后在我的包含和引用中使用完全相同的别名

include: [{model: Products, attributes: [], as: 'products'}]

attributes: [ ... , [Sequelize.col('products.product_name', 'product_name')]

没有 raw: true 就像一个魅力:) 谢谢@Emma !!!

请使用Sequelize.col包裹嵌套的列,以便Sequelize可以正确地为该列起别名。

Orders.findAll({
  include: [
    {model: Products, attributes: []}
  ],
  attributes: ['id_order', 'dtime_order', 'amount', [Sequelize.col('products.product_name'), 'product_name']],
  raw: true
})