【问题标题】:How to Apply IF Where Condition in Laravel Collation如何在 Laravel 排序规则中应用 IF Where 条件
【发布时间】:2020-02-03 21:20:36
【问题描述】:

我需要从数组事件中收集我的票部分,我的条件是

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

但是上面的查询并没有返回实际结果。

谢谢

【问题讨论】:

    标签: laravel collect laravel-6


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,我是 laravel 的新手,这就是为什么会发生这种情况...,我会尝试您的回答。
    猜你喜欢
    • 2022-01-24
    • 2018-05-09
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2018-09-19
    • 2021-11-25
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多