laravel - How to Apply IF Where Condition in Laravel Collation
问题描述
I need to collect my ticket sections from the array event, and my condition is
if 'custom_times' == 'yes'
then pick up ticket section with only
section_end_time < current date
Sample array Format
{"event_id":1,"ticket_type":"event", "custom_times":"yes",.....,"ticket_section":[{"section_id":1,"section_end_time":"2019-10-10 12:12:12",..... }]}
Query
$ticket_sections = collect($event->ticket_sections)->map(function($sections) {
return $sections;
})->where('ticket_type', 'event')
->where('hide_online', 'no')
->when('custom_times' == 'yes', function($query){
return $query->where('section_end_time', '<' ,$event->current_date_time);
});
But the above query not return the actual result.
Thanks
解决方案
我认为您将集合与查询生成器混淆了。
集合的when方法需要一个布尔值才能工作,并且不能与集合成员上的条件一起工作。
以下是您可以执行所需操作的方法:
$ticket_sections = collect($event->ticket_sections)
->where('ticket_type', 'event')
->where('hide_online', 'no')
->filter(function($section) use ($event) {
return $section->custom_times !== 'yes'
|| $section->section_end_time < $event->current_date_time;
});
推荐阅读
- view - 为视图链接 3 种类型的文档
- powershell - Powershell 后续用户名
- ios - 使用 uiscrollview 的图像缩放意外工作。迅速
- python - 找出 for item in list 和 for number in range 之间的区别
- coldfusion - Coldfusion - 防止直接访问用户创建的要下载的文件
- asp.net-mvc - 如何检查用户是否是组成员
- vba - 通过vba为ms word中的文本添加阴影
- visual-studio-code - 使用在 Windows 10 中运行的 VSCode 调试在 WSL 中运行的 Java
- php - 只显示不在其他表 laravel 中的项目
- html - 响应式网格宽度不同高度列