【问题标题】:How to correctly configure and count a belongsToMany association in Sequelize?如何正确配置和计算 Sequelize 中的 belongsToMany 关联?
【发布时间】:2020-03-31 03:04:33
【问题描述】:

我在 Sequelize 中遇到了这个 belongsToMany 的问题。

我正在创建一个视频内容网站。一个视频可以在多个列表中,显然,一个列表可以有多个视频(n:n)。一个视频只能属于一个频道 (1:n)。 列表、视频和频道与帐户相关联(均为 1:n)。

我想获取所有列表以及每个列表中的视频数量。

所以我以这种方式创建模型:

视频:

export class Video extends Model {
  public static associations: {
    channel: BelongsTo;
    account: BelongsTo;
    list: BelongToMany;
  };

  public id: string;
  public title: string;
  public desc: string;
  public createdAt: Date;
  public updatedAt: Date;

  public channelId: string;
  public channel: Channel;
  public getChannel: BelongsToGetAssociationMixin<Channel>;
  public setChannel: BelongsToSetAssociationMixin<Channel, string>;

  public accountId: string;
  public account: Conta;
  public getAccount: BelongsToGetAssociationMixin<Account>;
  public setAccount: BelongsToSetAssociationMixin<Account, string>;
}

Video.init(
  {
    title: STRING(100),
    descricao: STRING(500),
  },
  {
    sequelize,
    modelName: 'videos',
    hooks: {
      beforeCreate: (model, options) => {
        model.id = uuidv4();
      }
    }
  }
);

import { Channel } from './channels';
export const channel = Video.belongsTo(Channel, { foreignKey: 'channelId' });

import { Account } from './accounts';
export const account = Video.belongsTo(Account, { foreignKey: 'accountId' });

import { List } from './lists';
export const lists = Video.belongsToMany(List, {
  foreignKey: 'videoId' ,
  through: 'videos_list',
  timestamps: false
});

列表:

export class List extends Model {
  public static associations: {
    account: BelongsTo;
    videos: BelongsToMany;
  };

  public id: string;
  public name: string;
  public desc: string;
  public createdAt: Date;
  public updatedAt: Date;

  public accountId: string;
  public account: Conta;
  public getAccount: BelongsToGetAssociationMixin<Account>;
  public setAccount: BelongsToSetAssociationMixin<Account, string>;

  public videos: Video[];
  public getVideos: BelongsToManyGetAssociationsMixin<Video>;
  public setVideos: BelongsToManySetAssociationsMixin<Video, string>;
  public addVideo: BelongsToManyAddAssociationMixin<Video, string>;
  public addVideos: BelongsToManyAddAssociationsMixin<Video, string>;
  public createVideo: BelongsToManyCreateAssociationMixin<string>;
  public countVideos: BelongsToManyCountAssociationsMixin;
  public hasVideo: BelongsToManyHasAssociationMixin<Video, string>;
  public removeVideo: BelongsToManyRemoveAssociationMixin<Video, string>;
  public removeVideos: BelongsToManyRemoveAssociationsMixin<Video, string>;
}

Lista.init(
  {
    name: STRING(100),
    desc: STRING(500),
  },
  {
    sequelize,
    modelName: 'lists',
    hooks: {
      beforeCreate: (model, options) => {
        model.id = uuidv4();
      }
    }
  }
);

import { Account } from './accounts';   
export const account = Lista.belongsTo(Account, {
  foreignKey: 'accountId',
  as: 'account'
});

import { Video } from './videos';
export const videos = List.belongsToMany(Video, {
  foreignKey: 'listId',
  through: 'videos_list',
  timestamps: false
});

我正在做这样的查询:

  List.findAll({
    attributes: [
      'name', 'desc',
      [ Sequelize.fn("COUNT", Sequelize.col("videos.id")), "countVideos" ]
    ],
    include: [{ model: Video, as: 'videos', attributes: [] }],
    group: ['videos.listId'],
    order: [['name', 'DESC']]
  })

但我收到以下错误:

DatabaseError [SequelizeDatabaseError]: column videos.listId does not exist

我在这里做错了什么?

我只列出了我认为相关的列表和视频模型。如果您需要其他任何内容,请告诉我,我会提供。

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    List.belongsToMany(Video... 中,您将videoId 作为FK 而不是listId

    【讨论】:

    • 这是一个错字。在代码中没问题。更正了它。谢谢。
    • 好的,还有一件事 - 您正在查询包含视频的列表,并且您想按 video.listId 进行分组,但视频模型没有 listId 字段,这就是它不起作用的原因。试试 list.id 吧?
    • 我试过group: ['"lists"."id"'],现在我得到了DatabaseError [SequelizeDatabaseError]: column "videos-&gt;videos_list.listId" must appear in the GROUP BY clause or be used in an aggregate function
    • 对表“videos_list”的 FROM 子句条目的引用无效
    • 我不是 sequelize 分组方面的专家,但我知道 sequelize 对连接表有点奇怪。如果您只想计算视频,我建议您在 List 和 VideosList 之间创建一个额外的关联(一对多)并以这种方式进行查询。应该没问题。我已经看到它多次建议多对多问题。我自己在用。
    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多