问题描述
我将感谢您对解决此问题的任何帮助。我正在从事 Laravel 项目。我有一个这样的收藏;
$products = Product::all();
集合中的每个产品都有一个名为 status 的列,该列设置为 0、1 或 2。现在我想遍历我的集合,如果所有产品状态值都返回 0,我想在前端,否则显示其他内容。我已经尝试过了,但无法达到我想要的效果;
$status = 0;
foreach($products as $product){
if($product->status == 0{
$status = 0;
return "exhausted";
}
return "not exhausted";
}
解决方法
您可以使用Collection::every()
:
if ($products->every(fn($product) => $product->status === 0)) {
return "exhausted";
}
return "not exhausted";
,
那怎么办,如果只有当所有状态都为 0 时:
$status = "exhausted";
foreach($products as $product){
if($product->status != 0){
$status = "not exhausted";
break;
}
}
return $status;
,
可以使用 Eloquent 获取一个 Collection,然后使用 Collection 的 count 方法。示例:
$products = Product::all();
$count = $products->whereStatus(0)->get()->count();
return $count == 0 ? "Exhausted": "WhatEverYouwant";