Typescript Sequelize,M:M关系,查询仅返回单个条目

时间:2018-07-05 19:47:04

标签: node.js postgresql typescript sequelize.js nestjs

我将NestJs框架与Sequelize Typescript一起用于Node,我试图在用户和网页之间创建多对多关系,使许多用户可以在其收藏夹中拥有相同的网站

现在我的问题是,当我进行查询时,它会将结果限制为单个条目,而直接使用完全相同的查询直接查询数据库时,则会返回所有预期的条目。

这是我的NestJs收藏夹实体,在其中定义了收藏夹表:

// favorite.entity.ts

import { Table, Column, Model, PrimaryKey, ForeignKey, BelongsTo, NotNull } from "sequelize-typescript";
import { IDefineOptions } from "sequelize-typescript/lib/interfaces/IDefineOptions";
import { UserEntity } from "../users/user.entity";
import { SiteEntity } from "../sites/site.entity";

const tableOptions: IDefineOptions = {
  timestamp: true,
  tableName: "favorites",
  schema: process.env.DB_SCHEMA,
} as IDefineOptions;

@Table(tableOptions)
export class FavoriteEntity extends Model<FavoriteEntity> {
  @BelongsTo(() => UserEntity)
  user: UserEntity;

  @ForeignKey(() => UserEntity)
  @PrimaryKey
  @NotNull
  @Column
  userId: number;

  @BelongsTo(() => SiteEntity)
  site: SiteEntity;

  @ForeignKey(() => SiteEntity)
  @PrimaryKey
  @NotNull
  @Column
  siteId: number;
}

我进行Sequelize查询的服务:

// favorite.service.ts

import { Inject, Injectable } from "@nestjs/common";
import { Model } from "sequelize-typescript";
import { IFavoriteService } from "./interfaces";
import { FavoriteEntity } from "./favorite.entity";

@Injectable()
export class FavoriteService implements IFavoriteService {
  constructor(
    @Inject("FavoriteRepository") private readonly favoriteRepository: typeof Model,
    @Inject("SequelizeInstance") private readonly sequelizeInstance,
  ) {}

  public async findByUserId(userId: number): Promise<FavoriteEntity | null> {
    return await FavoriteEntity.scope().find<FavoriteEntity>({
      logging: console.log,
      where: { userId },
    });
  }
}

已注销的SQL语句为:

Executing (default): SELECT "userId", "siteId" FROM "public"."favorites" AS "FavoriteEntity" WHERE "FavoriteEntity"."userId" = '1';

结果是一个条目(数据库中有很多行)...

{
    "userId": 1,
    "siteId": 1650
}

我是否在实体中犯了一些错误,或者可能是在我的续集查询中?

谢谢!

2 个答案:

答案 0 :(得分:0)

mottosson您确定同一条SQL查询返回很多行吗?因为那会很奇怪。

答案 1 :(得分:0)

如果您使用findAll而不是find,会得到什么结果。但是我同意查询看起来不错