筛选子集合中的laravel集合



我的收藏是这样的。

Collection {
0 => Name_Model {
"id" => 44
"name" => "The name of "
"list_angg" => Collection {
0 => Name_Model_sub {
"code" => "02"
"nameofcode" => "The name of 02"
}
1 => Name_Model_sub {
"code" => "01"
"nameofcode" => "The name of 01"
}
}
}
1 => Name_Model {
"id" => 45
"name" => "The name of thus"
"list_angg" => Collection {
0 => Name_Model_sub {
"code" => "03"
"nameofcode" => "The name of 3"
}
}
}
}

我想用list_angg->code的值来过滤那个模型。所以我试着这样做。list_angg->code的过滤和预处理

$jurnals = $filterCollection->filter(function($value, $key) use ($kode_fakultas){
foreach ($value->list_angg as $lists) {
$filtered = $lists->where('code', $kode_fakultas);
return $filtered;
}
return $filtered;
});
dd($jurnals);

我尝试使用方法reject()map()。但过滤器不能正常工作。我错过什么了吗?

希望我能正确理解这个问题。

要筛选list_angg->code具有给定值的所有元素,可以使用filter()contains()的组合。

$filterCollection->filter(function ($value) use ($code) {
return $value->list_angg->contains('code', $code);
});
  • filter()返回集合中返回真实值的所有值。

  • 如果集合包含与所提供条件匹配的值,则contains()返回truefalse,该值可以是闭包、值或键和值。

记住CCD_;松散的";比较,所以如果您需要严格匹配,可以使用containsStrict

您的代码过滤不正确,因为在过滤器闭包中,您总是返回模型实例,该实例根据第一个元素计算为truefalse,因此它被视为通过或失败。

参考文献:

  • https://laravel.com/docs/8.x/collections#method-包含
  • https://laravel.com/docs/8.x/collections#method-过滤器
  • https://laravel.com/docs/8.x/collections#method-集装箱

您可以根据自己的需求首先重组集合来实现这一点。例如:

public function formatCollection($collection)
{
$results = [];
foreach ($collection as $item)
{
$results[] = [
'foe' => $item['bar'],
'baz' => $item['foo']
];
}
return collect($results);
}

这将返回所需的json格式,之后您可以对其应用过滤器。例如:

$result = formatCollection($collection);

这将返回您可以应用的集合

$result->filter(function(value){
return (value === 'foo');
}

这将返回集合中所需的信息或模型。

最新更新