使用 Laravel 9 中的范围比较两个相关表中的两列
我正在尝试创建一个范围来比较两个相关表上的两列。
根据这些表,我希望能够获取 ServiceCall
模型的所有实例,其中 next_service_date
在接下来的 15 天内,其中 Customer
code> 模型的 last_contact_date
值为 null
值,或者该值位于 ServiceCall
的 next_service_date
之前。
相关表结构:
customers
- id
- last_contact_date
service_calls
- id
- customer_id
- 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 客户.last_contact_date < service_calls.next_service_date 具有范围吗?
到目前为止,这就是我所拥有的,它可以完成除上述之外的所有操作。
客户型号:
public function scopeNotContacted(Builder $builder): Builder
{
return $builder->whereNull('last_contact_date');
}
ServiceCall 型号:
public function scopeUpcoming(Builder $builder): Builder
{
return $builder->whereBetween('next_service_date', [
Carbon::today(),
Carbon::today()->addDays(15)
])->whereHas('customer', fn ($builder) => $builder->notContacted());
}
谢谢!
I'm trying to create a scope that will compare two columns on two related tables.
Based on these tables I would like to be able to get all instances of the ServiceCall
model where the next_service_date
is within the next 15 days, where the Customer
model either has a null
value for the last_contact_date
or where it's before the ServiceCall
's next_service_date
.
Relevant table structure:
customers
- id
- last_contact_date
service_calls
- id
- customer_id
- next_service_date
Working SQL for what I'm trying to accomplish:
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);
Is there a way to accomplish this part of the SQL customers.last_contact_date < service_calls.next_service_date
with scopes?
This is what I have so far which does everything except the above.
Customer model:
public function scopeNotContacted(Builder $builder): Builder
{
return $builder->whereNull('last_contact_date');
}
ServiceCall 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());
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够使用附加软件包 kirschbaum-deefluctment/ /a>
中删除了范围:
我从
customer
Model ServiceCall模型I was able to solve this using an additional package kirschbaum-development/eloquent-power-joins
I removed the scope from the
Customer
modelServiceCall model: