Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用filter方法过滤Laravel雄辩集合_Php_Laravel_Laravel 4_Laravel 5 - Fatal编程技术网

Php 用filter方法过滤Laravel雄辩集合

Php 用filter方法过滤Laravel雄辩集合,php,laravel,laravel-4,laravel-5,Php,Laravel,Laravel 4,Laravel 5,有人能纠正这个代码吗。内部过滤器不工作。无论是否应用过滤器,结果都相同。我需要根据条件应用这样的批次过滤器您不必使用其中的where条件,您只需从回调中返回true或false,具体取决于选择条件 以下代码将仅保留通过给定真理测试的事件: $events=Event::all(); if (isset($scheduling) && $scheduling!=="All") { $events = $events->filter(function($e

有人能纠正这个代码吗。内部过滤器不工作。无论是否应用过滤器,结果都相同。我需要根据条件应用这样的批次过滤器

您不必使用其中的where条件,您只需从
回调中返回
true
false
,具体取决于选择条件

以下代码将仅保留通过给定真理测试的
事件

  $events=Event::all();
  if (isset($scheduling) && $scheduling!=="All")
  {
     $events = $events->filter(function($event) use ($scheduling)
     {
        return $event->where('scheduling',$scheduling);
      });
   }
  $events=$events->get();

另一个答案正确地解释了为什么您所做的工作不起作用,但这里有另一个选项

您可以使用构建器让数据库进行过滤,而不是从数据库中提取所有内容,然后对集合应用过滤器

   $events=Event::all();

   if (isset($scheduling) && $scheduling!=="All") 
   {  
      $events = $events->filter(function($event) use ($scheduling)
      {
         return $event->scheduling == $scheduling;
       });
    }

   dd($events); //Collection

可能是最后一行,在那里你重新分配了$events。我有很多过滤器,一个接一个。我认为创建这么多新的variablesHow来检查aray中是否有$scheduling不是一个好主意。你如何从模型类中正确使用该方法?我的意思是,如果在模型类中设置一个方法
$query = Event::query();
if (isset($scheduling) && $scheduling !== "All") {
    $query = $query->where('scheduling', '=', $scheduling);
}
// add more wheres as needed
$events = $query->get();