英文:
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
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论