Sequelizeで多対多のテーブルジョインを定義する
一つの記事には複数の著者が存在し(共同著者)、著者には複数の記事が結びつく場合、中間テーブルを利用して多対多の状態をつくれるようにしなければならない。
そのように行う方法を説明する。
これには、 belongsToMany
を利用することで多対多のデータ構造を作成することができる。
簡易的な書き方を紹介して、その次に、 as
や foreignKey
を使って細かいことをできる指定の仕方を紹介する。
定義は以下。
Article.belongsToMany(author.factory(sequelize), { through: "ArticleAuthor" });
使い方は以下。
const findAllIncludeParams: IncludeOptions[] = []; findAllIncludeParams.push({ model: Author, attributes: [], required: true }); Article.findAndCountAll({ include: findAllIncludeParams })
これにもっと細かい指定をすると、以下のようになる。
もし、 Article-Author
間の連結が1種類でない場合は、 as
で別名をつけることで、 複数の Article-Author
の連結を行うことができる。
定義は以下。
Article.belongsToMany(author.factory(sequelize), { as: "essay", through: "articleAuthor", foreignKey: "articleId", otherKey: "authorId" }); Article.belongsToMany(author.factory(sequelize), { as: "novel", through: "articleAuthor", foreignKey: "articleId", otherKey: "authorId" });
使い方は以下。
findAllIncludeParams.push({ as: "aaa", model: Author, });