用3个表对嵌套的关联进行排序

时间:2019-01-21 13:04:12

标签: node.js nested associations sequelize.js

我对查询关联有一点问题,我嵌套了关联(4个表,UsersABC,{{1} } hasOne UsersA hasMany A属于 B,{{ 1}} 属于 Users有很多 BA 属于 C

当我在C上执行findOne时,包括我的其他3个表:

B

我正确地获得了搜索到的行,但是问题出在第三个关联(表Users)的左外部联接查询上,生成的查询是

Models.User.findOne({
  where: { id: req.user.id },
  include:[{
    model: Models.Candidate, // Candidate Associations (user.candidate) (Table A)
    as: 'candidate',
    include:[{
      model: Models.Experience, // (Table B) Experiences Associations (user.candidate.experiences)
      as: 'experiences',
      include: [{
        model: Models.Service,
        as: 'service'
      }
      }] // Service Associations (Table C)
    }]
  }]
})

但是我想要这个查询:

C

那我该怎么办?

我在Google以及其他论坛和网站上搜索了一些帮助,但几周后一直找不到答案。

非常感谢您为我提供的帮助!

编辑:

这是我的模特:

用户:

LEFT OUTER JOIN `Services` AS `candidate->experiences->service` ON `candidate->experiences`.`id` = `candidate->experiences->service`.`id` 

候选人(A):

LEFT OUTER JOIN `Services` AS `candidate->experiences->service` ON `candidate->experiences`.`service_id` = `candidate->experiences->service`.`id` 

经验(B):

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    role: {
      type: DataTypes.STRING
    },
    type: {
      type: DataTypes.ENUM,
      values: ['admin', 'candidate', 'es', 'demo'],
      allowNull: false
    }
  });
  User.associate = function (models) {
    User.hasOne(models.Candidate, {
      foreignKey: 'user_id',
      as: 'candidate'
    });
  };
  return User;
};

服务(C):

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Candidate = sequelize.define('Candidate', {
    user_id: {
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    es_id: DataTypes.INTEGER,
    description: DataTypes.TEXT,
    photo: DataTypes.STRING,
    video: DataTypes.STRING,
    status: DataTypes.STRING,
    note: DataTypes.STRING,
    views: DataTypes.INTEGER
  }, {});
  Candidate.associate = (models) => {
    Candidate.belongsTo(models.User, {
      foreignKey: 'id',
      onDelete: 'CASCADE'
    });
    Candidate.hasMany(models.Experience, {
      foreignKey: 'candidate_id',
      as: 'experiences'
    });
  };
  return Candidate;
};

0 个答案:

没有答案