我如何获取与连接表中的条件具有多对多关系的相关行的计数

问题描述 投票:0回答:1

我对

sequelize
v6 有问题。我有两个具有多对多关系的表:
User
Pet
(id为uuidv4字段)。在联结表中,我有两个外键和一个自定义参数。

我如何从联结表中获取与一个用户(通过 user.id)相关的所有宠物以及自定义条件?

架构

// User
{
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  ...
}

// Pet
{
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  ...
}

// UserPet
{
  userId: DataTypes.UUID,
  petId: DataTypes.UUID,
  owner: DataTypes.BOOLEAN,
}

合伙人

// UserPet
static associate() {
  User.belongsToMany(Pet, { through: UserPet });
  Pet.belongsToMany(User, { through: UserPet });
}

类方法

// User
declare getPets: BelongsToManyGetAssociationsMixin<Pet>;
declare addPet: BelongsToManyAddAssociationMixin<Pet, string>;
declare addPets: BelongsToManyAddAssociationsMixin<Pet, string>;
declare setPets: BelongsToManySetAssociationsMixin<Pet, string>;
declare removePet: BelongsToManyRemoveAssociationMixin<Pet, string>;
declare removePets: BelongsToManyRemoveAssociationsMixin<Pet, string>;
declare hasPet: BelongsToManyHasAssociationMixin<Pet, string>;
declare hasPets: BelongsToManyHasAssociationsMixin<Pet, string>;
declare countPets: BelongsToManyCountAssociationsMixin;

我用过什么,但没用:

const user = await User.findOne(1);

// For one pet with condition
user.getPet({
  where: { 
    [Op.and]: { id: req.params.petId, owner: true },
  },
});

// For many pets with condition
user.getPets({
  where: { 
    owner: true,
  },
});

谢谢!

javascript sequelize.js sequelize-typescript
1个回答
0
投票

您需要先更新关联并确保模型定义正确。

User.belongsToMany(Pet, { through: UserPet });
Pet.belongsToMany(User, { through: UserPet });

UserPet.belongsTo(User, { foreignKey: 'userId' });
UserPet.belongsTo(Pet, { foreignKey: 'petId' });

User.hasMany(UserPet, { foreignKey: 'userId' });
Pet.hasMany(UserPet, { foreignKey: 'petId' });

“要获取与一个用户(通过 user.id)相关的所有宠物,并从联结表中获取自定义条件”=>

我们必须使用基于 UserPet 表的 User ID 连接 User 和 Pet 表。

这里,condition对象用于过滤UserPet联结表。

async function getAllPetsByUserID(userId, condition) {
  const userPets = await User.findOne({
    where: { id: userId },
    include: {
      model: Pet,
      through: {
        where: cond, // { owner: true }
        attributes: [],
      },
    },
  });

  return userPets ? userPets.pets : [];
}
© www.soinside.com 2019 - 2024. All rights reserved.