Laravel选择状态等于

huangapple go评论61阅读模式
英文:

Laravel Select where status equals

问题

我有2个模型

  1. 患者 模型带有 id, name, address
  2. 预约 模型带有 id, patient_id, appointment_date, status

患者 模型有多个 预约

我想要列出患者,其中患者的上一个预约 status='closed'。因为我不想向预约状态为 open 的患者添加新预约。

我该如何使用 Eloquent 实现这个目标?

英文:

I have 2 models

  1. Patient model with id, name, address
  2. 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')

huangapple
  • 本文由 发表于 2023年5月24日 22:17:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定