On this page
直播间评论情况
数据表迁移文件
shell
npx sequelize migration:generate --name=comment
js
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
return queryInterface.createTable("comment", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
content: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "评论内容",
},
live_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "直播间id",
references: {
model: "live",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
user_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "用户id",
references: {
model: "user",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
created_time: DATE,
updated_time: DATE,
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable("comment");
},
};
模型:app/model/comment.js
js
module.exports = (app) => {
const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;
const Comment = app.model.define("comment", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
content: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "评论内容",
},
live_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "直播间id",
references: {
model: "live",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
user_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "用户id",
references: {
model: "user",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
created_time: DATE,
updated_time: DATE,
});
// 关联关系
Comment.associate = function (models) {
// 关联发布人
Comment.belongsTo(app.model.User);
// 关联直播间
Comment.belongsTo(app.model.Live);
};
return Comment;
};
控制器:app/controller/admin/live.js
js
// 弹幕记录
async comment(){
const { ctx, app } = this;
const id = ctx.params.id
let res = await app.model.Comment.findAll({
where:{
live_id:id
},
include:[{
model:app.model.User,
attributes:['id','username','avatar']
}]
})
ctx.apiSuccess({
ths:[{
title: '内容',
key: 'content',
},{
title: '发送人',
key: 'username',
},{
title: '发送时间',
key: 'created_time',
}],
data:res.map(item=>{
return {
content:item.content,
created_time:app.formatTime(item.created_time),
username:item.user.username,
avatar:item.user.avatar,
}
})
})
}
路由:app/router.js
js
router.get("/admin/live/comment/:id", controller.admin.live.comment);