Sequelize在id上连接两个表。

huangapple go评论68阅读模式
英文:

Sequelize join two tables on id

问题

我有一个书籍用户表和一个电影用户表。我试图返回前100名电影观众的列表,以及他们的书籍资料信息。我想要根据用户ID进行连接,但似乎找不到正确的语法。

这是我尝试过的代码:

const mostActiveMovieWatchers = await MovieWatchers.findAll({
      order: [
        ['moviesWatched', 'DESC'],
      ],
      limit: '100',
      include: [{
        model: BookReaders,
        where: { 
          userId: '$MovieWatchers.id$'
        },
        required: true
      }]
    });

我还看到了一些示例,其中 where 子句看起来像这样:where: ['userId = id']

英文:

I have a table of book users and a table of movie users. I'm trying to return a list of the top 100 movie viewers, along with their book profile information. I want to join on ids, but I can't seem to find the right syntax.

This is what I've tried:

const mostActiveMovieWatchers = await MovieWatchers.findAll({
      order: [
        ['moviesWatched', 'DESC'],
      ],
      limit: '100',
      include: [{
        model: BookReaders,
        where: { 
          userId: '$MovieWatchers.id$'
        },
        required: true
      }]
    });

I've also seen examples where the where clause looks something like this where: ['userId = id']

答案1

得分: 0

Before join tables you need create association:

BookReaders.hasMany(MovieWatchers, { foreignKey: 'bookId' });

MovieWatchers.belongsTo(BookReaders, { foreignKey: 'bookId' });

Then, you can use the include option in a find or findAll method call on the MovieWatchers model to specify that you want to include the associated BookReaders data:

MovieWatchers.findAll({
  include: [
    {
      model: BookReaders,
    },
  ],
}).then((movies) => {
  // array of movies including books
});
英文:

Before join tables you need create association:

BookReaders.hasMany(MovieWatchers, { foreignKey: 'bookId' });

MovieWatchers.belongsTo(BookReaders, { foreignKey: 'bookId' });

Then, you can use the include option in a find or findAll method call on the MovieWatchers model to specify that you want to include the associated BookReaders data:

MovieWatchers.findAll({
  include: [
    {
      model: BookReaders,
    },
  ],
}).then((movies) => {
  // array of movies including books
});

huangapple
  • 本文由 发表于 2023年1月5日 23:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75020440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定