多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ### 模型静态属性 * [ ] 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; } ~~~