遵循关于association的association.js
文档,在sequelizejs 4.42.0
中加入用户和消息模型(postgres):
const { Event } = require('../models/event');
const { Message} = require('../models/message');
const { User } = require('../models/user');
module.exports = function() {
Message.belongsTo(User, {foreignKey: "sender_id"});
Message.belongsTo(Event, {foreignKey: "event_id"});
};
这是SQL连接代码:
require("../startup/association");
let messages = await Message.findAll({where: {event_id : req.query.event_id, fort_token: req.user.fort_token},
attributes: {exclude: ['fort_token']},
include: [{
model: User,
on: {
col1: db.where(db.col("Message.fort_token"), "=", db.col("User.fort_token")),
col2: db.where(db.col("Message.sender_id"), "=", db.col("User.id"))
},
attributes: ['id', 'name', 'user_data']
}],
order: ['createdAt']
});
上面的SQL代码抛出错误:
Executing (default): SELECT "message"."id", "message"."event_id", "message"."sender_id", "message"."data", "message"."createdAt", "user"."id" AS "user.id", "user"."name" AS "user.name", "user"."user_data" AS "user.user_data" FROM "messages" AS "message" LEFT OUTER JOIN "users" AS "user" ON "Message"."fort_token"="User"."fort_token" AND "Message"."sender_id"="User"."id" WHERE "message"."event_id" = '1' AND "message"."fort_token" = '12345678901234567890' ORDER BY "message"."createdAt";
Err in retrieving messages : missing FROM-clause entry for table "Message"