0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sequelizeでビット演算を使った検索を行う

Posted at

以下のようなテーブルがあるとします。
statusの値は10進数ですが、アプリケーションではビット演算で管理されてることがわかると思います。

id:1, status:1 // 1つめのフラグが立っている
id:2, status:4 // 3つめのフラグが立っている
id:3, status:1023 // 全てのフラグが立っている

SQLでの書き方

3つめのフラグが立っているかどうかのクエリーは以下になります。

xxx.sql
SELECT * FROM xxx WHERE (status & 4) = 4;

idが2,3が出力されます。

Sequelize.whereを使った書き方

xxx.ts
Model.findAll({
    where: sequelize.where(sequelize.literal('status & 1023'), 1023)
})

参考

https://github.com/sequelize/sequelize/issues/5207
https://lambdalisue.hatenablog.com/entry/2013/12/22/041347
https://sequelize.org/master/manual/model-querying-basics.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?