英文:
Laravel Select where status equals
问题
我有2个模型
- 患者 模型带有
id,name,address - 预约 模型带有
id,patient_id,appointment_date,status
患者 模型有多个 预约。
我想要列出患者,其中患者的上一个预约 status='closed'。因为我不想向预约状态为 open 的患者添加新预约。
我该如何使用 Eloquent 实现这个目标?
英文:
I have 2 models
- Patient model with
id,name,address - Appointment model with
id,patient_id,appointment_date,status
Patient model has many Appointments.
I want to list Patients where patient's previous Appointment status='closed' only. Beacause I dont want to add new appointment to a patient whose appointment status is open
How can I achieve this with eloquent ?
答案1
得分: 1
你可以使用Eloquent查询具有所需条件的患者:
use App\Models\Patient;
$patients = Patient::whereHas('appointments', function ($query) {
$query->where('status', 'closed');
})->get();
希望这有所帮助!
英文:
you can query the patients with the desired condition using Eloquent:
use App\Models\Patient;
$patients = Patient::whereHas('appointments', function ($query) {
$query->where('status', 'closed');
})->get();
Hope this helps!
答案2
得分: 0
使用 whereNotIn 来排除仅具有状态为 "open" 的 ID,并返回所有患者:
$Patients = Patient::whereNotIn('id', function($query){
return $query->select('patient_id')->distinct('patient_id')->from('appointments')->where('status', '=', 'open');
})->get();
这个 Eloquent 查询与 SQL 中的查询相同:
select * from `patients` where `id` not in (select distinct `patient_id` from `appointments` where `status` = 'open')
英文:
Use whereNotIn for excluding only the id's that have status open and return all the patients:
$Patients = Patient::whereNotIn('id', function($query){
return $query->select('patient_id')->distinct('patient_id')->from('appointments')->where('status', '=', 'open');
})->get();
This eloquent query is same as in sql :
select * from `patients` where `id` not in (select distinct `patient_id` from `appointments` where `status` = 'open')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论