如何使用Prisma基于一对多关联字段编写过滤查询?
Prisma关联模型过滤查询解决方案
针对你的Car和Booking一对多关联场景,要筛选出预订记录满足特定startDate和endDate条件的车辆,核心是利用Prisma关联过滤的操作符,以下是不同场景的实现方案:
场景1:存在至少一条符合时间条件的预订的车辆
如果需要返回有至少一条预订在指定时间段内的车辆,同时可选择性加载这些符合条件的预订记录:
const targetStart = new Date('2024-01-01'); const targetEnd = new Date('2024-01-31'); const carsWithMatchingBookings = await prisma.car.findMany({ where: { bookings: { // 匹配存在至少一条符合条件的预订 some: { startDate: { gte: targetStart }, endDate: { lte: targetEnd } } } }, // 可选:仅加载符合条件的预订,而非该车辆的所有预订 include: { bookings: { where: { startDate: { gte: targetStart }, endDate: { lte: targetEnd } } } } });
场景2:所有预订都符合时间条件的车辆
如果需要筛选出每一条预订都在指定时间段内的车辆:
const targetStart = new Date('2024-01-01'); const targetEnd = new Date('2024-01-31'); const carsAllBookingsMatching = await prisma.car.findMany({ where: { bookings: { // 要求所有预订都满足时间条件 every: { startDate: { gte: targetStart }, endDate: { lte: targetEnd } } } }, include: { bookings: true } // 加载所有预订用于验证 });
场景3:指定时间段内无预订(可用车辆)
如果要查找在目标时间段内没有被预订的车辆(即无时间重叠的预订),可以用none操作符:
const desiredStart = new Date('2024-02-01'); const desiredEnd = new Date('2024-02-05'); const availableCars = await prisma.car.findMany({ where: { bookings: { // 不存在任何与目标时间段重叠的预订 none: { startDate: { lte: desiredEnd }, endDate: { gte: desiredStart } } } } });
关键说明
- Prisma针对一对多关联提供
some/every/none三个核心过滤操作符,分别对应「存在匹配」「全部匹配」「无匹配」三种逻辑 - 若要同时过滤关联数据,需在
include的子字段中单独添加where条件,否则默认返回该车辆的所有预订记录 - 时间比较使用Prisma内置操作符:
gte(大于等于)、lte(小于等于)、gt(大于)、lt(小于),可根据实际需求调整
内容的提问来源于stack exchange,提问作者larcMetournel
相关产品推荐
相关产品推荐

