【问题标题】:how to get rows that has at least 1 association row with sequelize如何获取至少有 1 个关联行与 sequelize 的行
【发布时间】:2020-07-24 00:58:03
【问题描述】:

我有这样的“成分”和“日志”表

[Ingredient Table]
id 
..
...
[Log Table]
id
Ingredient_id
record_date
..
...

关系是Log.belongsTo(Ingredeint)

我怎样才能找到至少有 1 行 Log 的所有成分?

我的意思是当我搜索成分时,如果没有相关的登录成分,我不想在我的搜索结果中包含该成分。

我现在所做的是

const ingredients = await Ingredient.findAll({
    include: {
      model: Log
    },
    group: "id",
    attributes: {
      include: [
        [sequelize.fn("COUNT", sequelize.col("record_date")), "order_count"]
      ]
    }
  })

const sortedIngredient = ingredients
      .filter(ingredient => ingredient.dataValues.order_count > 0)

但我认为会有更好的方法。

感谢您阅读本文。

【问题讨论】:

    标签: mysql sequelize.js associations


    【解决方案1】:

    如果我对您的理解正确,您想在您的包含中进行内连接,那么您只会返回在包含的模型中具有某些匹配的成分。

    尝试将包含更改为:

    include: {
      model: Log
      required: true, // <-- Add this row
    }
    

    有关 require 的更多信息可以在文档中找到:https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll

    另一个可能对您有所帮助的选项是添加 have 以过滤聚合列,如下所示:

    const ingredients = await Ingredient.findAll({
      include: {
        model: Log,
      },
      group: "id",
      attributes: {
        include: [
          [sequelize.fn("COUNT", sequelize.col("record_date")), "order_count"],
        ],
      },
      having: sequelize.literal("`order_count` > 0"), // <-- Add this row
    });
    

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2019-05-07
      • 2014-02-11
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多