如何在 Laravel 排序规则中应用 IF Where 条件

How to Apply IF Where Condition in Laravel Collation

我需要从阵列事件中收集我的门票部分,我的条件是

if 'custom_times' == 'yes' 

然后取票区只有 section_end_time < current date

示例数组格式

 {"event_id":1,"ticket_type":"event", "custom_times":"yes",.....,"ticket_section":[{"section_id":1,"section_end_time":"2019-10-10 12:12:12",..... }]}

查询

$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);
  });

但上面的查询不是return实际结果。

谢谢

我认为您将集合与查询生成器混淆了。

集合的 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;
  });