Anthony O
Anthony O

Reputation: 653

How can I have a Sequelize composite key a (non-unique, unique) pair and then use it to map associations?

enter image description here

I have these relations in my SQL database. There are two entity types A and B. These entities are owners of a resource and I manage this via a mapping table. The relations are:

Entity A has one or more Owner entries. Entity B has one or more Owner entries.

Each Owner entry has zero or one Entity A entry. Each Owner entry has zero or one Entity B entry.

Each Resource has zero or more owners. Each Owner entry tracks one resource.

I am using this to model individuals and groups owning a resource. The problem is when I go to use the ORM it complains that I have not given an association between Owners and Entities. I'm not really sure how to do this with Sequelize. What I would like to do is have a composite key like so:

(entity_type, entity_id)

where entity_type is from enum (EntityA, EntityB) and entity_id is an id corresponding to a record in either of those tables. In this way I can guarantee that the composite key is unique. But again, I'm not really sure how I can implement this via Sequelize.

Upvotes: 0

Views: 102

Answers (1)

Wang Liang
Wang Liang

Reputation: 4434

While make associate, we can use where condition as below code.

Model : Owner.js

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
    class Owner extends Model {
        static associate(models) {
            // define association here
            this.belongsTo(models.EntityA, {
                foreignKey: "entity_id",
                as: "A",
                where: { entity_type: 0 }
            });
            this.belongsTo(models.EntityB, {
                foreignKey: "entity_id",
                as: "B",
                where: { entity_type: 1 }
            });

        }
    }
    Owner.init({
        entity_type: DataTypes.INTEGER,
        entity_id: DataTypes.INTEGER,
    }, {
        sequelize,
        modelName: "Owner"
    });
    return Owner;
};
db.Owner.findAll({
    include: 'A', 'B'
});

Upvotes: 1

Related Questions