0

I've 3 models: A, B, and its pivot, AsBs. I'm trying to get all A/B entities (querying its respective repositories) where pivot's boolToCheck is true. I've been able to filter through each other model's fields (ex: A where B.bField is whatever), but not through a pivot field.

How could I do it? Thanks!

Model A

module.exports = (sequelize, DataTypes) => {
  const A = sequelize.define(
    "a",
    {
      aField: {
        allowNull: false,
        type: DataTypes.STRING,
      },
    },
    {}
  );
  A.associate = function (models) {
    A.belongsToMany(models.B, {
      through: "asBs",
      onDelete: "RESTRICT",
      onUpdate: "CASCADE",
    });
  };
  return A;
};

Model B

module.exports = (sequelize, DataTypes) => {
  const B = sequelize.define(
    "b",
    {
      bField: {
        allowNull: false,
        type: DataTypes.STRING,
      },
    },
    {}
  );
  B.associate = function (models) {
    B.belongsToMany(models.A, {
      through: "asBs",
      onDelete: "RESTRICT",
      onUpdate: "CASCADE",
    });
  };
  return B;
};

PIVOT AB

module.exports = (sequelize, DataTypes) => {
  const AsBs = sequelize.define(
    "asBs",
    {
      aId: {
        allowNull: false,
        type: DataTypes.NUMBER,
      },
      bId: {
        allowNull: false,
        type: DataTypes.NUMBER,
      },
      boolToCheck: {
        allowNull: false,
        type: DataTypes.NUMBER,
      },
    },
    {}
  );
  AsBs.associate = function (models) {
    AsBs.belongsTo(models.A, {
      onDelete: "RESTRICT",
      onUpdate: "CASCADE",
    });
    AsBs.belongsTo(models.B, {
      onDelete: "RESTRICT",
      onUpdate: "CASCADE",
    });
  };
  return AsBs;
};
  • Maybe you can try to query AsBs and include both A and B? That way you can add conditions for all three models – Anatoly Oct 28 '20 at 15:45
  • I realized that when asking this question...Still, I'd rather not use AsBs (if possible), since it involves having to create its controller and repository and it could be a little confusing (if I want A data, should i query A or should I query AsBs?) – Alex Corregidor Oct 29 '20 at 07:19
  • 1
    Just use AsBs model as a service model. No need to create its own controller. When you work with `A` controller you also use `B` and `AsBs` models to include what you want. If you returning a list of `A` even if through AsBs that wouldn't be bad at all – Anatoly Oct 29 '20 at 07:22

0 Answers0