When using Sequelize, I encountered a lot of problems with model association, and the official documentation was patchy.

For example

model.user{
id:INTERGER,
institution_id:INTERGER
}

model.institutions{
id:INTERGER,
name:STRING
}
Copy the code

Use examples to clarify the logic

Suppose I now have a requirement query user and the organization to which I belong; Then, in terms of association, I need to identify the user first, and then check the user’s organization according to the user’s institution_id. That is, the left link query

LEFT OUTER JOIN `institutions` AS `institution` ON `user`.`institution_id` = `institution`.`id`;
Copy the code

So the SQL code that needs to be compiled looks like this, and I need to associate it, and how do I do that.

model.user.associate= function (models) {
    models.user.belongsTo(models.institutions, {
        foreignKey: 'institution_id',
        targetKey: 'id',
        constraints: false})},Copy the code

The source model is User, and the target model is institutions, so the user as the main relationship is found to be the foreignKey of user ===institution targetKey; The data detected were dominated by users and supplemented by institutions

Suppose I now have a requirement query user and the organization to which I belong; OUTER JOIN user AS user ON institutions.id = user.institution_id; So the SQL code that needs to be compiled looks like this, and I need to associate it, and how do I do that.

model.user.associate= function (models) {
    models.institutions.institutions(models.user, {
            foreignKey: 'institution_id'.sourceKey: 'id',
            constraints: false})},Copy the code

The source model is institutions, and the target model is User. Therefore, the sourceKey of institutions === foreignKey of institutions can be found by taking institutions as the main relationship. The data detected were those of institutions dominated and users supplemented