[英]Compare two columns from two related tables using scopes in Laravel 9
我正在嘗試創建一個 scope 來比較兩個相關表上的兩列。
基於這些表,我希望能夠獲取ServiceCall
model 的所有實例,其中next_service_date
在接下來的 15 天內,其中Customer
model 的last_contact_date
值為null
或者它在ServiceCall
的next_service_date
之前。
相關表結構:
顧客
服務電話
為我想要完成的工作工作 SQL:
SELECT service_calls.next_service_date, customers.last_contact_date FROM service_calls
INNER JOIN customers ON service_calls.customer_id = customers.id
WHERE service_calls.next_service_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 15 DAY)
AND (customers.last_contact_date < service_calls.next_service_date OR customers.last_contact_date IS NULL);
有沒有辦法用范圍完成 SQL customers.last_contact_date < service_calls.next_service_date
的這一部分?
這是我到目前為止所做的一切,除了上述。
客戶model:
public function scopeNotContacted(Builder $builder): Builder
{
return $builder->whereNull('last_contact_date');
}
服務電話 model:
public function scopeUpcoming(Builder $builder): Builder
{
return $builder->whereBetween('next_service_date', [
Carbon::today(),
Carbon::today()->addDays(15)
])->whereHas('customer', fn ($builder) => $builder->notContacted());
}
謝謝!
我能夠使用額外的 package kirschbaum-development/eloquent-power-joins來解決這個問題
我從Customer
model 中刪除了 scope
服務電話 model:
public function scopeNotContacted($builder)
{
$builder->joinRelationship('customers', function ($join) {
$join->where(function ($query) {
$query->whereNull('customers.last_contact_date')
->orWhereRaw('customers.last_contact_date < service_calls.next_service_date');
});
});
}
public function scopeUpcoming($builder)
{
$builder->whereBetween('next_service_date', [
Carbon::today(),
Carbon::today()->addDays(15)
])->notContacted();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.