Typeorm:如何按关系查询

时间:2019-01-23 08:09:29

标签: javascript node.js typescript typeorm

如何使用Active Record模式按关系查询?

我有2个实体,但想通过查询第二个来获取:

角色:

import { User } from "./User";

@Entity({ name: "roles" })
export class Role extends BaseEntity {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public name: string;

  @CreateDateColumn()
  public createdAt: string;

  @UpdateDateColumn()
  public updatedAt: string;

  @OneToMany(() => User, user => user.role)
  public users: User[];
}

用户:

@Entity({ name: "users" })
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public email: string;

  @Column()
  public name?: string;

  @Column({ select: false })
  public passwordSalt: string;

  @Column({ select: false })
  public passwordHash: string;

  @CreateDateColumn()
  public createdAt: string;

  @UpdateDateColumn()
  public updatedAt: string;

  @Column()
  public roleId: number;

  @ManyToOne(() => Role, role => role.users, {
    eager: true
  })
  @JoinColumn()
  public role: Role;
}

我想按Role.name查询用户并按Role.createdAt排序,我编写了buildQuery函数来为用户模型建立查询并将查询传递给findAndCount

buildQuery:

export default function buildQuery ({
  name,
  email,
  roleName,
  orderByRoleCreatedAt,
  limit,
  offset
}: IUsersQuery) {
  const query = {};

  if (name) {
    set(query, "where.name", Like(`${name}%`));
  }

  // how find users by user.role.name ???
  if (roleName) {
    set(query, "where.role.name", Like(`${roleName}%`));
  }

 // how order users by user.role.createdAt ASC ???
  if (orderByRoleCreatedAt) {
    set(query, "order.role.createdAt", orderByRoleCreatedAt);
  }

  if (email) {
    set(query, "where.email", Like(`${email}%`));
  }

  set(query, "skip", offset);
  set(query, "take", limit);

  return query;
}

User.findAndCount(buildQuery(params));

0 个答案:

没有答案