blog

Sequelizeのマルチテーブル動的条件付きクエリがページングをサポートする。

I. モデルの記述\n連想関係\n連想関係の使用法\nUserテーブルとAccountテーブルは1対1のリレーションシップで、Accountテーブルは外部キーuser_idを持っています:\nUser...

Nov 21, 2020 · 3 min. read
シェア

I. 書き込みModel

人間関係



scope条件クエリ

次にController

マルチテーブルルックアップ

  1. 使い方
    User.hasOne(Account,{foreignKey:'user_id'})
    Account.blongsTo(User,{ foreignKey: 'user_id' })
    
  2. ソースコード
    ...
    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; 
}
Read next

ユーザーはiOS 7について再び不満を漏らしている:これらは最悪の問題である!

iOS 7の登場は目覚ましく、アップグレードした人もしていない人も、iOS 7について少しは知っていることでしょう。iOS 7の変更点は好意的に受け止められている一方で、他の機能については賛否両論があります。そしてこの記事では、iOS 7のどの問題がユーザーの間で最も物議を醸しているかに焦点を当てています!以下からご覧ください!

Nov 21, 2020 · 2 min read