eggjs,分页条件查询,模糊查询,联合查询

  1. 分类,作者,来源,镇区,模型里关联新闻表
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,查询的地方也要对应使用as

  1. service里写查询语句,分页,条件,模糊,关联
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
        }
    }

你可能感兴趣的:(eggjs,分页条件查询,模糊查询,联合查询)