如果我有使用 Sequelize 的自定义外键,如何添加关联?

问题描述 投票:0回答:1

我正在尝试在下面提供的模型列表和用户之间建立关联。我已经在列表表上使用“用户”列创建了一个自定义外键。我将如何着手建立这个协会?因为我使用的控制器具有以下逻辑。但我收到“SequelizeEagerLoadingError”,所以我知道它与关联有关。谢谢!

const listings = await Listing.findAll({
    include: [{
        model: User,
        attributes: ['name', 'email']
    }]
});

上市模型

const Sequelize = require('sequelize');
const {sequelize} = require('../database/connect.js');
const User = require('./User.js');

const Listing = sequelize.define('listings', {
    // Column Definitions ...
    user: {
        type: Sequelize.DataTypes.INTEGER,
        allowNull: false,
        validate: {
            notEmpty: {
                args: [true],
                msg: 'Must Provide Listing User'
            }
        },
        references: { 
            model: User, 
            key: 'id'
        }
    }
}, {timestamps: true, freezeTableName: true, hooks: {
    
}});

// **Define the Association Here ...**

async function syncTable() {
    await Listing.sync();
    console.log(`Listing Table Created if it doesn't exist. And doing nothing if it already exists`);
}

syncTable();

module.exports = Listing;

用户模型

const Sequelize = require('sequelize');
const {sequelize} = require('../database/connect.js');
const bcrypt = require('bcryptjs');
const path = require('node:path');
const fs = require('node:fs');
const Listing = require('./Listing.js');

const User = sequelize.define('users', {
     // Column Definitions ...
}, {timestamps: true, freezeTableName: true, hooks: {
    
}});

// Define the Association Here ...

async function syncTable() {
    await User.sync();
    console.log(`User Table Created if it doesn't exist. And doing nothing if it already exists`);
}

syncTable();

module.exports = User;

我尝试了以下关联,但不确定它们是否正确

Listing.belongsTo(User, {foreignKey: 'user', targetKey: 'id', as: 'userDetails'}); 当我使用这段代码👆时,我没有收到任何错误。

User.hasMany(列表); 当我使用这段代码👆时,我确实收到了错误。它说它们是模型导入/导出中的问题,但这不是真的,因为它对列表关联说了同样的事情,但最终在使用选项对象后,错误消失了。

node.js model sequelize.js associations
1个回答
0
投票

您只需要使用相同的

foreignKey
选项及其值定义两个关联,请参阅我的答案

Listing.belongsTo(User, { foreignKey: 'user', as: 'userDetails'});
User.hasMany(Listing, { foreignKey: 'user', as: 'listings' });
© www.soinside.com 2019 - 2024. All rights reserved.