【问题标题】:Remove/unset specific row from collection in Laravel从 Laravel 的集合中删除/取消设置特定行
【发布时间】:2022-11-04 06:18:02
【问题描述】:

我有这个雄辩的询问

 $result= Result::query()
            ->where('city_id', '=', $search_city)
            ->get();
        } 

然后在循环内

 foreach($result as $row)
                {
                    if(isset($row->user_id) && $row->user_id!=0)
                    {
                        $UserDetails = User::where('id',$row->user_id)->first();
                        if($UserDetails) 
                        {
                            if($UserDetails->type=='normal user')
                            {
                              // remove this specific row from result 
                            }
                
                        }
                    } 
                }

在 if 条件中,如果满足特定条件,我只想从结果中删除该特定行。

 return view('index', compact('result'));

任何解决方案谢谢

【问题讨论】:

  • foreach($result as &$row) { ... if() { ... if() { if() { unset($row); } } } } 应该可以工作。但如果你能解释你到底想做什么,那么我们可以提出一些更好的解决方案。 :)
  • 我想您可能正在寻找 forget($key) 中描述的 laravel.com/docs/9.x/collections#method-forget 方法
  • @OMiShah 我尝试取消设置它不起作用
  • @Techno 这是为 laravel 5 看标签
  • 真正的问题是,您为什么不更改查询,使其首先不在集合中?看看whereHas()

标签: laravel laravel-5 eloquent


【解决方案1】:

只需用户 ->filter() 即可排除您原始收藏中的项目...

$results = $results->filter(function($result){
   $user = User::where('id',$result->user_id)->first();
   if (!$user) return true; // Include
   if ($user->type == 'normal user') return false; // Exclude
   return true; // Include
});

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2016-10-01
    • 2013-05-01
    • 2014-05-31
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多