eggjs,分頁條件查詢,模糊查詢,聯(lián)合查詢

  1. 分類,作者,來源,鎮(zhèn)區(qū),模型里關聯(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,查詢的地方也要對應使用as

  1. service里寫查詢語句,分頁,條件,模糊,關聯(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
        }
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容