简体   繁体   English

使用Sequelize.js创建JOIN WHERE键IN(SELECT键FROM ...)

[英]Making a JOIN WHERE key IN(SELECT key FROM…) using Sequelize.js

Im a noob in Sequelize.js and somewhat less in Angular but must solve a problem in which I want to use a subquery as a condition of a JOIN. 我是Sequelize.js中的菜鸟,而Angular中的菜鸟稍微少一点,但必须解决我想使用子查询作为JOIN条件的问题。 I paste some examples below because code says more then words. 我在下面粘贴了一些例子,因为代码说的多于单词。

SQL SQL

INNER JOIN table ON table.key IN(SELECT current_key FROM historysnake WHERE original_key IN(
       SELECT original_key FROM historysnake WHERE current_key = table.key)
AND historysnake.model = 'tablename')

The question is: How can I put above query into a Sequelize object? 问题是:如何将上述查询放入Sequelize对象? Something like: 就像是:

Sequelize.js Sequelize.js

var foo = sequelize.define('foo', {...}, {
    classMethods: {
        associate: function(models) {
            foo.hasMany(...)
        }
    }
});

Ok, here's an example, which assumes that PK of PatientEvents is the original_key on all the history rows: 好的,这是一个例子,它假设PatientEvents的PK是所有历史行上的original_key:

PatientEvents.hasMany(HistorySnake, {foreignKey : 'original_key'});

PatientEvents.findAll({
   include: [{
       model: HistorySnake,
       required : true,      // true = INNER JOIN but you might need outer join to see events with no history
       where : { modelName : 'PatientEvents' }  // as needed
       }],
   where: { patient_name : 'xyz' }  // as needed
   })        

I figured it out. 我想到了。 I'm not really sure if @KenOn10's answer would've worked. 我不确定@ KenOn10的答案是否有效。 I'm too much of a noob on this subject for that but thanks for the answer anyway. 对于这个问题,我对这个问题太过分了,但不管怎样,谢谢你的回答。

I ended up specifying my own 'on' clause like this. 我最终指定了我自己的'on'子句。

models.Aim.find({
    include: [{
        model: models.ObjectiveReport,
        required: false,
        where: ['ObjectiveReports.report_entrydate >= ?', show_date],
            on: {
                aim_id: sequelize.literal('aim.aim_id IN(SELECT current_key FROM historysnake WHERE original_key IN(SELECT original_key FROM historysnake WHERE current_key = aim.aim_id) AND historysnake.model = "aim")')
            })
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM