如何在序列表中关联表

时间:2019-01-14 12:42:46

标签: node.js postgresql sequelize.js

我有此功能,将需要查询3个不同的表。 下表如下:

DelegateUserLink

id
DelegateId (int)
UserId (int)

Delegate

id (int)
createdBy (int)

User

id (int)
name (varchar)

我首先以这种方式创建关联:

models.DelegateUserLink.belongsTo(models.Delegate);
models.Delegate.belongsTo(models.User, {through: models.Delegate.createdBy});

我运行然后查询如下:

return models.DelegateUserLink.findAll({
        where: { UserId: id }
        ,include: {model: models.Delegate,attributes: ['createdBy'],include: {model: models.User,attributes: []}}
    }).then(function(rs) {
        rs.forEach(function(result) {
            console.log("result:",result);
        });
        return rs;
    });

执行此查询会出现此错误:

SequelizeDatabaseError: column Delegate.UserId does not exist        

查看生成的查询,我会看到:

SELECT "DelegateUserLink"."createdAt", "DelegateUserLink"."updatedAt", "DelegateUserLink"."DelegateId", "DelegateUserLink"."UserId", "Delegate"."id" AS "Delegate.id", "Delegate"."createdBy" AS "Delegate.createdBy" FROM "DelegateUserLinks" AS "DelegateUserLink" LEFT OUTER JOIN "Delegates" AS "Delegate" ON "DelegateUserLink"."DelegateId" = "Delegate"."id" LEFT OUTER JOIN "Users" AS "Delegate->User" ON "Delegate"."UserId" = "Delegate->User"."id" WHERE "DelegateUserLink"."UserId" = 677; 

我的想法是通过使用此行告诉sequelize在连接表DelegateUser时使用哪个字段

models.Delegate.belongsTo(models.User, {through: models.Delegate.createdBy});

在我指定“通过”的地方应该进行联接。但显然我是错的。因为它尝试使用不存在的Delegate.UserId(并给出错误)。加入时如何指定使用哪个字段?

1 个答案:

答案 0 :(得分:1)

好吧,这是关于使用关键字“ foreignKey”的,就像这样:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.lux.escanor.myapplication"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}