简体   繁体   English

sequelize AresToMany where过滤器

[英]sequelize belongsToMany where filter

Let's say I have the following models: 假设我有以下模型:

const Item = sequelize.define("Item", {
    active: { type: DataTypes.BOOLEAN, defaultValue: true },
    name: { type: DataTypes.STRING, allowNull: false },
    description: { type: DataTypes.TEXT } 
  });


const Partner = sequelize.define("Partner", {
    active: { type: DataTypes.BOOLEAN, defaultValue: true },
    name: { type: DataTypes.STRING, allowNull: false },
  });

I associate them the following way: 我通过以下方式将它们关联:

models.Item.belongsToMany(models.Partner, {
      as: "vendors",
      through: "PartnerDefaultItems"
    });

models.Partner.belongsToMany(models.Item, {
      as: "items",
      through: "PartnerDefaultItem"
    });

I guess my models and associations are okay because it will create a new table in the database with item and partner ids. 我想我的模型和关联还可以,因为它将在数据库中使用项目和合作伙伴ID创建一个新表。

Now! 现在! I'm doing server side pagination with filtering, and when I select a partner (or more) I only want to return those items associated with the selected partner(s). 我正在使用过滤进行服务器端分页,当我选择一个或多个伙伴时,我只想返回与所选伙伴关联的那些项目。

Can I do it with only one query? 我可以只执行一个查询吗?

For example: my frontend sends a request with partnerId: 1... 例如:我的前端发送一个带有partnerId:1 ...的请求。

const res = await db.models.Item.findAll({
          where: {select every item with associated partnerId}
        });

//-associated table example-// //关联表示例-//

partner_id: 1 item_id: 1 => partner.partnerId equals with partner_id so select item where item.id = item_id partner_id:1 item_id:1 => partner.partnerId等于partner_id,因此请选择item,其中item.id = item_id

partner_id: 2 item_id: 2 => partner.partnerId not equals, don't select partner_id:2 item_id:2 => partner.partnerId不等于,请勿选择

etc... 等等...

The point is to use single query for this, without any raw sql. 关键是为此使用单个查询,而无需任何原始sql。

Your query structure should include the related table and specify the through relationship as well as the where for your partnerId . 您的查询结构应include相关的表,并指定through关系,以及在where为您partnerId You can enable logging: true to show the SQL query in the console for further debugging. 您可以启用logging: true以在控制台中显示SQL查询以进行进一步调试。

const res = await db.models.Item.findAll({
  include: [
    {
      model: db.models.Parter,
      as: 'partners',
      through: 'PartnerDefaultItem',
      where: {
        id: partnerId,
      },
    },
  ],
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM