I. 書き込みModel
人間関係
scope条件クエリ
次にController
マルチテーブルルックアップ
- 使い方
User.hasOne(Account,{foreignKey:'user_id'}) Account.blongsTo(User,{ foreignKey: 'user_id' })
- ソースコード
... User.associate = function() { app.model.User.hasOne(app.model.Account, { foreignKey: 'user_id' }); app.model.User.hasMany(app.model.Log, { foreignKey: 'user_id', targetKey: 'log_id' }); }; ...
第三に、マルチテーブル動的条件付きクエリのネイティブな実装です。
sequelize.js
databaseディレクトリにsequelize.jsファイルを追加しました。
const users = await this.ctx.model.Account.scope([{ method: [ 'hasStatus', status ] }]).findAndCountAll();
env
...
scopes: {
hasName(e = false) {
if (!e) return {};
return {
where: { name: { [Op.like]: `%${e}%` } },
};
},
hasEnterprise(e = false) {
if (!e) return {};
return {
where: { enterprise: { [Op.like]: `%${e}%` } },
};
}
},
...
コントローラファイルの書き込み
//model
const { Op } = require('sequelize');
module.exports = app => {
const User = app.model.define('user',{},{
sequelize: app.Sequelize,
modelName: 'user',
tableName: 'user',
//scope条件付きクエリをサポートするために最も重要なことを以下に挙げる。
scopes: {
hasName(e = false) {
if (!e) return {};
return {
where: { name: { [Op.like]: `%${e}%` } },
};
},
hasEnterprise(e = false) {
if (!e) return {};
return {
where: { enterprise: { [Op.like]: `%${e}%` } },
};
}
},
});
//マルチテーブルクエリの連想関係
User.associate = function() {
app.model.User.hasOne(app.model.Account, { foreignKey: 'user_id' });
app.model.User.hasMany(app.model.Log, { foreignKey: 'user_id', targetKey: 'log_id' });
};
return User;
}