筛选集合并删除集合 eloquent laravel

Filter the collections and remove a collection eloquent laravel

我想从集合中删除过滤后的集合,就像我有这个返回的集合一样。

$products = items::where('item_id',$request->item_id)->with('product_reviews')->with('product_reviews.profile')->get();
foreach($products->product_reviews as $r):
    if($r->status==='unapproved'):
        //remove this from 'products' collections because its not approved yet
        $this->remove($this);
    endif;
endforeach;

但是这个

$this->remove($this);

不起作用,也不是删除集合的有效语法,我只是不知道如何删除过滤后的集合,例如如果列状态包含 'unapproved'。有什么想法,请帮忙?

您可以在关系中添加条件。这未经测试,但很可能会解决您的问题。

items::where('item_id',$request->item_id)->with([
   'product_reviews' => function ($query) {
       $query->where('status', 'approved')->with('profile');
    }
])->get();

嗯..有点奇怪,因为其他 2 个解决方案应该适用于您的情况。

您是否尝试过过滤对象并将其传递给其他数组并在您的视图中显示它们?喜欢:

$productWithReviews = items::where('item_id',$request->item_id)->with('product_reviews')->get();
$products = [];
foreach($productWithReviews->product_reviews as $r):
    if($r->status!=='unapproved'):
        $products[] = $r;
    endif;
endforeach;