使用Sequelize.jsjoin特定的列

我正在尝试使用Sequelize.js在特定列上join一些表格。

到目前为止,我的代码是这样的:

table_1.findall({ include: [{ model: table_2 attributes: ['id', 'another_id'] include: [{ model: table_3 required: true attributes: ['time'] }] }] }) 

每个表的主键都是“id”。

这似乎等同于下面的SQL(为了简洁起见,我显示了SELECT *,因为这不是这个问题的焦点):

 SELECT * FROM table_1 as t1 LEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id INNER JOIN table_3 as t3 ON t2.id = t3.t2_id 

我想有这样的东西:

 SELECT * FROM table_1 as t1 LEFT OUTER JOIN table_2 as t2 ON t1.id = t2.t1_id INNER JOIN table_3 as t3 ON t2.another_id = t3.t2_id 

有没有办法强制t2和t3之间的连接使用t2的主键之外的东西?

我在Sequelize文档中find了[options.include [] 。on ],但不知道用什么语法来提供我自己的ON条件。

您想要在模型的classMethods部分中定义的关联中定义特殊外键名称。 下面是一个连接到users表两次的表的例子,它具有特殊的外键:

 classMethods: { associate(models) { this.belongsTo(models.user, { foreignKey: 'created_by_user_id', as: 'created_by', }); this.belongsTo(models.user, { foreignKey: 'updated_by_user_id', as: 'updated_by', }); }, }, 

然后,在你的findAll ,不需要做任何特别的事情 – sequelize会自动知道外键列是什么。