简体   繁体   中英

Sequelize field association does not work

I have two tables. How to link field in first table with id field in second table in Sequelize?

First table:

tables.comments = sequelize.define('comments', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    text: Sequelize.TEXT,
    article: Sequelize.INTEGER,
    author: {
        type: Sequelize.INTEGER,
        references: "users",
        referencesKey: "id",
        allowNull: false
    },
    answer: Sequelize.INTEGER,
    rating: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    }
}, {
    classMethods: {
        associate: function(models) {
            tables.comments.belongsTo(tables.models.users, {foreignKey: 'author', targetKey: 'name'});
        }
    }
});

Second table:

tables.users = sequelize.define('users', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    mail: Sequelize.TEXT,
    name: Sequelize.TEXT,
    pass: Sequelize.TEXT,
    status: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    },
    rating: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    },
    ban: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    },
    key: Sequelize.TEXT
}, {
    classMethods: {
        associate: function(models) {
            tables.users.hasMany(tables.models.comments, {foreignKey: 'author'});
        }
    }
});

I need to get tables.comments, but where instead of "author" will be the name of the author of the tables.users. I make request:

tables.comments.findAll({inclide: [{model: tables.users}]}).then(function(comments) {
    console.log(comments);
});

But in result in fields author only number, not name from users ! Where is the mistake?

(Sorry for bad english)

In the associate classmethod, you'll want to use the column name of the table that the classmethod is defined in. I'm assuming that the join condition is comments.author = users.id .

For your comments table, it would be:

tables.comments.belongsTo(tables.models.users, {
  foreignKey: 'author'
});

For your users table, it would be:

tables.users.hasMany(tables.models.comments, {
  foreignKey: 'id'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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