gpt4 book ai didi

node.js - 这是一个 Node 数据库问题。我包括用户模型,但它不包括在结果中

转载 作者:行者123 更新时间:2023-12-03 22:23:22 25 4
gpt4 key购买 nike

api或路由器有什么问题?我肯定包含了用户模型 为什么没有包含用户信息?下面是加载现有帖子的 api 逻辑。

由于还需要作者信息,因此使用以下包含语法包含用户模型信息。

不打印用户信息。
是什么原因?

混帐
https://github.com/hyunsokstar/node_bird_22

接口(interface)代码

router.get('/', async (req, res, next) => { // GET /api/posts
try {
const posts = await db.Post.findAll({
include: [{
model: db.User,
attributes: ['id', 'nickname'],
}],
order: [['createdAt', 'DESC']], // DESC는 내림차순, ASC는 오름차순
});
console.log("posts : ", posts);

res.json(posts);
} catch (e) {
console.error(e);
next(e);
}
});

模型
// back\models\post.js

module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', { // 테이블명은 posts
content: {
type: DataTypes.TEXT, // 매우 긴 글
allowNull: false,
},
}, {
charset: 'utf8mb4', // 한글+이모티콘
collate: 'utf8mb4_general_ci',
});

Post.associate = (db) => {
db.Post.belongsTo(db.User); // 테이블에 UserId 컬럼이 생겨요
db.Post.hasMany(db.Comment);
db.Post.hasMany(db.Image);

// 릴레이션 관계 추가
db.Post.belongsTo(db.Post, { as: 'Retweet' }); // RetweetId 컬럼 생성
db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' });
};

return Post;

};


结果
  Post {
dataValues:
{ id: 21,
content: 'write test',
createdAt: 2019-11-07T09:43:00.000Z,
updatedAt: 2019-11-07T09:43:00.000Z,
UserId: 1,
RetweetId: null,
User: [User] },
_previousDataValues:
{ id: 21,
content: 'write test',
createdAt: 2019-11-07T09:43:00.000Z,
updatedAt: 2019-11-07T09:43:00.000Z,
UserId: 1,
RetweetId: null,
User: [User] },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Array],
includeNames: [Array],
includeMap: [Object],
includeValidated: true,
attributes: [Array],
raw: true },
isNewRecord: false,
User:
User {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } } ]

最佳答案

const where = {};
let options = { where };

options.include = [
{
model: db.User,
attributes: ['id', 'nickname'],
},
];
options.order = [['createdAt', 'DESC']];

const posts = await db.Post.findAll(options);

试试这个它会有所帮助

关于node.js - 这是一个 Node 数据库问题。我包括用户模型,但它不包括在结果中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com