续集:用户未与评论者关联

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

我正在使用两个 Sequelize 模型:用户和评论。每条评论属于一个用户,一个用户可以发表多条评论。我的目标是在 JSON 响应中包含与每个用户相关的所有评论。以下是

User
Commentaire
的相关模型:

用户型号:

`const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');

const Commentaire = sequelize.define('./Commentaire.js');

const User = sequelize.define('User', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
    },
    nom: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    prenom: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
    },
    phone: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    isActive: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
    date_add: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
    },
    verification: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    tags: {
        type: DataTypes.JSON,
        allowNull: false,
    },
    type: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: null,
    },
}, {
    timestamps: true,
    modelName: 'User', 
});




 User.associate = (models) => {
    User.hasMany(Commentaire, {
        foreignKey: 'user',
        as: 'commentaires'
    });
}; 


User.sync()
    .then(() => console.log('Modèle User synchronisé avec la base de données'))
    .catch(err => console.error('Erreur de synchronisation du modèle User:', err));

module.exports = User;
`

评论型号:

`const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');

const User = require('./User');

const Post = require('./Post');

const Commentaire = sequelize.define('Commentaire', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
    },
    commentaire: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    userId: { 
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: User,  
            key: 'id', 
        }
    },
    postId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: Post,  
            key: 'id', 
        }
    },
}, {
    timestamps: true, 
    modelName: 'Commentaire', 
});


Commentaire.associate = (models) => {
    Commentaire.belongsTo(User, {
        foreignKey: 'commentaires_ibfk_1', 
        as: 'id' 
    });
};
 


Commentaire.sync()
    .then(() => console.log('Modèle Commentaire synchronisé avec la base de données'))
    .catch(err => console.error('Erreur de synchronisation du modèle Commentaire:', err));

module.exports = Commentaire;
`

下面是index.js类:

`'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      file.indexOf('.test.js') === -1
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.User = require('./User')(sequelize);
db.Commentaire = require('./Commentaire')(sequelize);


module.exports = db;
`

这是我的功能`

exports.getByPost = async(req, res) => {
    try {
        const postId = req.params.post; 

        const comments = await Commentaire.findAll({
            where: { user: postId },
            include: [{
                model: User
            }],

        });

        if (!comments.length) { 
            return res.json({ message: 'Aucun commentaire trouvé pour ce post' });
        }

        res.json({ message: 'Commentaires récupérés avec succès', comments });
    } catch (error) {
        console.error(error);
        
        res.json({ message: 'Erreur lors de la récupération des commentaires', error });
    }
};

这是错误

EagerLoadingError [SequelizeEagerLoadingError]: User is not associated to Commentaire!
    at Commentaire._getIncludedAssociation (C:\work-space\test-topmorer\node_modules\sequelize\lib\model.js:565:13)
    at Commentaire._validateIncludedElement (C:\work-space\test-topmorer\node_modules\sequelize\lib\model.js:502:53)
    at C:\work-space\test-topmorer\node_modules\sequelize\lib\model.js:421:37
    at Array.map (<anonymous>)
    at Commentaire._validateIncludedElements (C:\work-space\test-topmorer\node_modules\sequelize\lib\model.js:417:39)
    at Commentaire.findAll (C:\work-space\test-topmorer\node_modules\sequelize\lib\model.js:1124:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
mysql node.js express orm sequelize.js
1个回答
0
投票

我以前也遇到过这个问题。查看您的代码,我认为您可以通过将 User 和 Commentaire 类之间的关联中的“commentaires_ibfk_1”更改为“userId”来解决它。

belongsTo 中的foreignKey 属性应与hasMany 中的foreignKey 属性匹配。

您的关联可能如下所示:

Commentaire.associate = (models) => {
    Commentaire.belongsTo(User, {
        foreignKey: 'userId', 
        as: 'id' 
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.