Eggjs 联表查询
查询 联表
2023-09-11 14:15:29 时间
实现:
通过 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; } }
.
相关文章
- ElasticSearch查询max_result_window问题处理
- MyBatis联表查询——别名方式
- linux磁盘空间查询
- sql随机查询数据语句(NewID(),Rnd,Rand(),random())
- 不得不看,只有专家才知道的17个SQL查询提速秘诀!
- Lucene5学习之FunctionQuery功能查询
- 通过命令名称查询进程id
- SqlServer查询语句中用到的锁
- [NHibernate]条件查询Criteria Query
- Python Django 惰性查询(懒加载)
- PHP查询登录中的sql注入
- MongoDB查询、索引和聚合
- Eclipse中java获得mysql的查询结果集
- 操作系统的时区设置会影响数据库查询SYSDATE和SYSTIMESTAMP的值