簡體   English   中英

維持多對多關系

[英]Sequelize many to many relationship

我需要一些幫助來解決多對多關系的問題。

我需要模型,客戶和服務(很多)。 現在,我想加載一個客戶端提供的所有服務(通過客戶端ID)。 包含條件如何看起來要實現這一目標?

服務:

var Service = sequelize.define('service', {
    title: {
      type: DataTypes.STRING(200),
      allowNull: false
    }
  },{
    paranoid: true,
    underscored: true,
    classMethods: {
      associate:function(models){
          Service.belongsToMany(models.client, { through: 'client_services' });
          Service.hasMany(models.rule, { foreignKey: 'service_id' })
      }
    }
  });

客戶:

 var Client = sequelize.define('client', {
    title: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    company: {
        type: DataTypes.STRING(200),
        allowNull: false
    },
    vendor: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    consumer: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true
    },
    address_id: {
      type: DataTypes.INTEGER,
      allowNull: true
    }
  },{
    paranoid: true,
    underscored: true,
    classMethods: {
      associate:function(models){
          Client.hasMany(models.service, { through: 'client_services'});
      }
    }
  });

在我的控制器中(無法正常運行:[錯誤:客戶端(客戶端)未與服務關聯!]):

var condition = {
      where: { 'client.id': req.user.client_id },
      include: [{ model: Client, as: 'client' }]
    }
Service.findAll(condition)
.then(responseWithResult(res))

確定where子句需要包含在模型的include中:

var condition = {
      include: [{ model: Client, where: { 'id': req.user.client_id } }]
    }
Service.findAll(condition)
.then(responseWithResult(res))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM