私には 2 つのエンティティ user と travel があり、熱心な読み込みとの多対多の関係があります。
旅行を読み込むときに、パスワードや作成日と更新日などを必要とせず、名前と ID だけを必要とするなど、すべてのユーザー詳細が返されることを望みません。
どうすればそうなりますか?
以下は私の 2 つのエンティティです。
旅行の実体
@Entity()
export class Trip {
@PrimaryGeneratedColumn()
id: number;
@Column()
@IsNotEmpty()
@Index({ unique: true })
name: string
@ManyToOne(type => User)
@JoinColumn()
owner: User
@Column()
@IsNotEmpty()
destination: string
@ManyToMany(type => User, {
eager: true
})
@JoinTable()
buddies: User[]
}
ユーザー エンティティ
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
@IsNotEmpty()
@Index({ unique: true })
username: string
@Column()
@IsNotEmpty()
firstName: string
@Column({ default: null })
lastName: string
@Column({ unique: true, default: null })
@Length(10, 12)
phonenumber: string
@Column()
@Length(8, 16)
password: string
@Column()
@CreateDateColumn()
createdAt: Date;
@Column()
@UpdateDateColumn()
updatedAt: Date;
@BeforeUpdate()
@BeforeInsert()
hashPassword() {
if (this.password) {
this.password = bcrypt.hashSync(this.password, 8);
}
}
checkIfUnencryptedPasswordIsValid(unencryptedPassword: string) {
return bcrypt.compareSync(unencryptedPassword, this.password);
}
}
次のように使用します
public doGetTripById = async (req: Request, res: Response) => {
const tripId = req.params.tripId;
const tripRepository = getRepository(Trip);
let trip: Trip;
try {
trip = await tripRepository.findOneOrFail({ where: { id: tripId } });
res.status(200).json(trip)
} catch (error) {
return res.status(400).json({ message: "Oops! somethig went haywire, possibly trip doesn't exist" })
}
}
以下の変更により必要な応答を得ることができましたが、満足できません。
trip.buddies.forEach(buddy => {
buddy.password = undefined
buddy.updatedAt = undefined
buddy.createdAt = undefined
buddy.phonenumber = undefined
})
------------------------
これで問題は解決できると思います
QueryBuilder オブジェクトを作成し、リレーション代入を追加する必要があります。外部テーブルにエイリアスを作成すると、必要な列を選択できます。
tripRepository.createQueryBuilder("Trip")
.innerJoinAndSelect("Trip.buddies", "Buddie")
.select(["Trip.id", "Trip.name", "Buddie.firstName", "Buddie.lastName"])
.where([...])
.getMany()
よろしく
共有
この回答を改善します
フォローする
2021 年 5 月 5 日 20:32 に回答
クリストロイヤー
クリストロイヤー
41
1
銅バッジ 1 個
1
こんにちは @cristroyer です。プロジェクトは中止されましたが、ご回答ありがとうございます。誰かのお役に立てれば幸いです - ありがとうございます。
– サヒル・パウデル
2021 年 5 月 7 日 3:27