使用 filter 方法过滤 Laravel eloquent 集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31657851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:03:31  来源:igfitidea点击:

Filtering Laravel eloquent collections with filter method

phplaravellaravel-4laravel-5

提问by phani

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

can some one correct this code. the inner filter is not working. the results are same with or without applying filters. i need to apply lot filters like this basing on conditions

有人可以更正此代码。内部过滤器不工作。无论是否应用过滤器,结果都相同。我需要根据条件应用这样的过滤器

回答by pinkal vansia

You don't have to use where condition in it, you can just return trueor falsefrom within callback, depending on the selection condition.

您不必在其中使用 where 条件,您可以直接 returntruefalsefrom inside callback,具体取决于选择条件。

Below code will keep only those eventsthat pass a given truth test:

下面的代码将只保留那些events通过给定真值测试的代码:

   $events=Event::all();

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

   dd($events); //Collection

Read More

阅读更多

回答by Don't Panic

The other answer correctly explains why what you're doing isn't working, but here is another option.

另一个答案正确地解释了为什么您正在做的事情不起作用,但这是另一种选择。

Instead of pulling everything from the database and then applying filters to the collection, you can use the builder to let the database do the filtering.

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

$query = Event::query();
if (isset($scheduling) && $scheduling !== "All") {
    $query = $query->where('scheduling', '=', $scheduling);
}
// add more wheres as needed
$events = $query->get();