實現:
通過 user表 關聯外鍵 查詢 role表 及 diary表
1.數據模型
app/model/user.js
/** * 用戶模型 */ module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, autoIncrement: true, primaryKey: true }, name: { type: STRING, allowNull: false }, email: { type: STRING, allowNull: false }, password: { type: STRING(32), allowNull: false }, avatar: { type: STRING, allowNull: true }, roleId: { type: INTEGER, allowNull: false, defaultValue: 6 } }); // 表關聯的字段 User.associate = function() { // 一對多 app.model.User.hasMany(app.model.Diary, { foreignKey: 'user_id', targetKey: 'id'}); /** * User.belongsTo(關聯的模型, { foreignKey: '使用什么字段關聯', targetKey: '與關聯的模型那個字段關聯', as: '別名' }); */ // 一對一 app.model.User.belongsTo(app.model.Role, { foreignKey: 'roleId', targetKey: 'id', as: 'role'}); } return User; }
app/model/role.js
/** * 角色模型 */ module.exports = app => { const { INTEGER, STRING } = app.Sequelize; const Role = app.model.define('role', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, name: STRING(50), pid: INTEGER }, { timestamps: false }); return Role; }
app/model/diary.js
/** * 日志模型 */ module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const Diary = app.model.define('diary', { id: { type: INTEGER, autoIncrement: true, primaryKey: true }, title: { type: STRING, allowNull: false }, content: { type: STRING, allowNull: false } }); // 表關聯的字段 Diary.associate = function() { app.model.Diary.belongsTo(app.model.User, { foreignKey: 'user_id', targetKey: 'id'}) } return Diary; }
2.關聯查詢
app/service/user.js
// 獲取用戶列表/詳情 async detail(id) { const { app } = this; try { if(id){ // return await app.model.User.findByPk(app.toInt(id)); return await app.model.User.findOne({ attributes: ['id','name','email','avatar','roleId'], where: { id }, include: [{ model: app.model.Role, as: 'role',//這里的 as需要與之前定義的as名字相同 }] }); } return await app.model.User.findAll({ attributes: ['id','name','email','avatar','roleId'], include: [{ model: app.model.Role, as: 'role',//這里的 as需要與之前定義的as名字相同 },{ model: app.model.Diary }] }); }catch(err){ console.log(err); return null; } }
.