【问题标题】:Output associated information from two tables in sequelize在 sequelize 中从两个表中输出关联信息
【发布时间】:2016-11-05 23:01:10
【问题描述】:

假设我有两个表:TradeSettingTradePrices。多个 TradeSettings 可以使用一个 TradePrice。在 Express 中,我想用相应的 TradePrice 列出所有 TradeSettings,因此我对两个表都使用了 sequelize 的 findAll 并将结果传递给我的玉视图。

我的问题:

如何在不为我的翡翠视图的每次迭代创建新选择的情况下为相应的 TradeSetting 输出正确的价格:

each tradeSetting in tradeSettings
  td #{tradeSetting.Name}
  td #{tradeSetting.PriceId}
  td // the according price for this tradeSetting

我考虑过使用关联数组之类的东西,以便可以使用 #{TradePrice[tradeSetting.PriceId]} 输出它,但我不确定这是否可行以及我需要做什么?

我的两张表看起来像这样(简化):

TradeSettings(Id、名称、PriceId

TradePrices(Id,价格)

旁注:我还没有在我的数据库中使用外键,但我可以在那里添加它们并在必要时相应地调整模型。

【问题讨论】:

    标签: mysql node.js express pug sequelize.js


    【解决方案1】:

    通过迭代您的TradeSettings 来预处理您的数据,为每个 TradeSetting 找到匹配的 TradePrice 并将其作为新属性保存到每个 TradeSetting 中。

    之后,每个 TradeSetting 都将其正确的 TradePrice 作为属性轻松访问(就像您访问 Name 或 PriceId 一样)。

    然后您可以轻松地遍历您的 TradeSettings 并在您的第三行 td 中(来自您的示例)您可以使用 #{tradeSetting.TradePrice.Price}

    编辑:您提到您正在使用 sequelize,如果可以在您的数据库中设置外键,那么您也可以使用它。 如果一切设置正确,请尝试

    TradeSetting.findAll({ include: [TradePrice])
    

    然后在你的玉模板中

    tradeSetting.get('TradePrice').get('Price')
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2016-07-23
      • 2021-03-05
      • 1970-01-01
      相关资源
      最近更新 更多