I have two tables, one about articles and the other about comments
//this is the table model of articles
module.exports = (app) => {
const { STRING, INTEGER, DATE } = app.Sequelize;
const Model = app.model.define(
"all_topics",
{
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
title: STRING(30),
content: STRING,
user_id: INTEGER,
created_at: DATE,
updated_at: DATE,
tag: STRING(30),
},
{
underscored: true,
}
);
Model.associate = function () {
Model.belongsTo(app.model.Users, { foreignKey: "user_id" });
Model.hasMany(app.model.Comments, {
foreignKey: "topic_id",
sourceKey: "id",
});
};
return Model;
};
//this is the table model of comments
module.exports = (app) => {
const { STRING, INTEGER, DATE } = app.Sequelize;
const Model = app.model.define(
"comments",
{
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
topic_id: INTEGER,
user_id: INTEGER,
parent_id: INTEGER,
content: STRING,
created_at: DATE,
},
{
timestamps: false,
freezeTableName: true,
underscored: true,
}
);
Model.associate = function () {
Model.belongsTo(app.model.Users, {
foreignKey: { user_id: "id", parent_id: "id" },
});
Model.belongsTo(app.model.AllTopics, {
foreignKey: "topic_id",
sourceKey: "id",
});
};
return Model;
};
//Query the article that specifies the id and the comments it contains
const Service = require("egg").Service;
class TopicLoadService extends Service {
async topicLoad(id) {
const { ctx } = this;
const topic = await ctx.model.AllTopics.findOne({
where: {
id,
},
include: [{ model: ctx.model.Comments }],
});
return { topic };
}
}
module.exports = TopicLoadService;
Foreign keys have been set up in the MySQL database But, an error was returned: Unknown column 'comments.userId' in 'field list'
The query statement it executes is
SELECT `all_topics`.`id`,
`all_topics`.`title`,
`all_topics`.`content`,
`all_topics`.`user_id`,
`all_topics`.`created_at`,
`all_topics`.`updated_at`,
`all_topics`.`tag`,
`comments`.`id` AS `comments.id`,
`comments`.`topic_id` AS `comments.topic_id`,
`comments`.`user_id` AS `comments.user_id`, //Queried
`comments`.`parent_id` AS `comments.parent_id`,
`comments`.`content` AS `comments.content`,
`comments`.`created_at` AS `comments.created_at`,
`comments`.`user_id` AS `comments.userId` //Why is this another query?
FROM `all_topics` AS `all_topics`
LEFT OUTER JOIN `comments` AS `comments`
ON `all_topics`.`id` = `comments`.`topic_id`
WHERE `all_topics`.`id` = '20000000';
I am a novice, some knowledge is not mastered, can you answer for me? Thank you very much