静态属性

优质
小牛编辑
139浏览
2023-12-01

模型静态属性

  • [ ] model 定义一个模型
    
    'use strict';

module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize;

const Post = app.model.define('post', {
    id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    title: STRING(30),
    content: STRING(255),
    user_id: INTEGER,
    created_at: DATE,
    updated_at: DATE,
});
// 模型实例添加关联
Post.associate = function() {
    app.model.Post.belongsTo(app.model.User, { as: 'user', foreignKey: 'user_id' });
};
// 模型实例添加静态方法
Post.findByIdWithUser = async function(id, userId) {
    return await this.findOne({
        where: { id, user_id: userId },
    });
};

return Post;

};

调用:

async update({ id, user_id, updates }) { const post = await this.ctx.model.Post.findByIdWithUser(id, user_id); if (!post) this.ctx.throw(404, 'post not found'); return post.update(updates); }

async find(id) { const post = await this.ctx.model.Post.findByPk(id, { include: [{ model: this.ctx.model.User, as: 'user', attributes: [ 'id', 'name', 'age' ], }], }); if (!post) { this.ctx.throw(404, 'post not found'); } return post; }