Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nest.js+mysql多表查询踩坑 #101

Open
lizhongzhen11 opened this issue Oct 8, 2020 · 0 comments
Open

nest.js+mysql多表查询踩坑 #101

lizhongzhen11 opened this issue Oct 8, 2020 · 0 comments

Comments

@lizhongzhen11
Copy link
Owner

花了我4个小时我才搞懂。。。

https://github.com/typeorm/typeorm/blob/master/docs/one-to-one-relations.md

// Entity
import { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from 'typeorm';
import { SYRole } from '../role/role.entity'

@Entity({
  name: 'SY_ManagerUser',
  synchronize: false
})
export class SYManagerUser {
  @PrimaryGeneratedColumn()
  userId: number;

  @Column()
  roleId: number;

  @Column({
    nullable: true
  })
  storeId: number | null;

  @Column({
    nullable: true
  })
  deptId: number | null;

  @Column({
    length: 10
  })
  userName: string;

  @Column({
    length: 10
  })
  nickName: string;

  @Column({
    length: 50
  })
  password: string;

  @Column({
    length: 15
  })
  phone: string;

  @Column({ 
    type: 'int',
    width: 1,
    default: 1 
  })
  status: number;

  @OneToOne(type => SYRole)
  @JoinColumn({
    name: 'roleId'
  })
  role: SYRole;
}


// service
@Injectable()
export class ManagerUserService {
  constructor(
    @InjectRepository(SYManagerUser)
    private managerUsersRepository: Repository<SYManagerUser>,
  ) {}

  async findAll(listbody: ListBody): Promise<ResponseData> {
    try {
      const current = listbody.current
      const result = await this.managerUsersRepository.findAndCount({
        skip: (current - 1) * 10,
        take: 10,
        relations: ["role"]
      });
      return Object.assign(SUCCESS, { data: result[0], current, pageSize: 10, total: result[1] })
    } catch (error) {
      console.log(error)
      return FAIL
    }
  }
}

最终结果:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant