- 分類,作者妻率,來(lái)源乱顾,鎮(zhèn)區(qū),模型里關(guān)聯(lián)新聞表
module.exports = (app) => {
const { STRING, INTEGER } = app.Sequelize;
const News = app.model.define(
"News",
{
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
title: STRING,
categoryLeave1: STRING,
categoryLeave2: STRING,
author: STRING,
from: STRING,
town: String,
desc: String,
imgList: String
},
{
tableName: "sys_news"
}
);
News.associate = function () {
app.model.News.belongsTo(app.model.Category, { foreignKey: 'categoryLeave1', targetKey: 'value', 'as': 'categoryLeave1Obj' })
app.model.News.belongsTo(app.model.Category, { foreignKey: 'categoryLeave2', targetKey: 'value', 'as': 'categoryLeave2Obj' })
app.model.News.belongsTo(app.model.Author, { foreignKey: 'author', targetKey: 'id' })
app.model.News.belongsTo(app.model.From, { foreignKey: 'from', targetKey: 'id' })
app.model.News.belongsTo(app.model.Town, { foreignKey: 'town', targetKey: 'id' })
}
return News;
};
特別注意宫静,belongsTo的用法走净,如果需要改名,需要使用as孤里。這里使用了as伏伯,查詢的地方也要對(duì)應(yīng)使用as
- service里寫查詢語(yǔ)句,分頁(yè)捌袜,條件说搅,模糊,關(guān)聯(lián)
async news(query) {
let where = {}
if (query.title) {
where.title = { [Op.like]: '%' + query.title + '%' }
}
if (query.author) {
where.author = query.author
}
if (query.from) {
where.from = query.from
}
if (query.town) {
where.town = query.town
}
if (query.categoryLeave1) {
where.categoryLeave1 = query.categoryLeave1
where.categoryLeave2 = query.categoryLeave2
}
const { count, rows } = await this.ctx.model.News.findAndCountAll({
where,
include: [
{ model: this.ctx.model.Category, attributes: ['label'], 'as': 'categoryLeave1Obj' },
{ model: this.ctx.model.Category, attributes: ['label'], 'as': 'categoryLeave2Obj' },
{ model: this.ctx.model.Author, attributes: ['label'] },
{ model: this.ctx.model.From, attributes: ['label'] },
{ model: this.ctx.model.Town, attributes: ['label'] }
],
offset: (query.currentPage - 1) * query.pageSize,
limit: parseInt(query.pageSize),
order: [['updated_at', 'DESC']]
})
return {
rows, count
}
}