
Collectionデータの数を条件を指定して抽出するときに利用します🐱
もくじ
こんな感じ
例)
[1, 2, 3, 4, 5]というデータから、3未満のデータを取得する
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->filter(function ($value, $key) {
return $value < 4;
});
$filtered->all();
// [1, 2, 3]
ここでtrueになるものを抽出するよ
return $value < 3;
だから、
[1, 2, 3]
と抽出できた!
実装例
// section_id配列取得
$r_president_content = app()->make(\App\Repositories\President\PresidentContentRepository::class)
$section_ids = $r_president_content->byWhere([
'president_id' => $president_administrator->president_id,
'company_id' => $section_company->id
])->pluck('connection_id');
// 公開済みのsection_idをfilter()で抽出
$r_section_content = app()->make(\App\Repositories\Section\SectionContentRepository::class);
$section_ids->filter(function ($item, $key) use ($is_publish, $r_section_content) {
$result = $r_section_content->byWhere([
'section_id' => $item,
'is_publish' => $is_publish, // 公開済み
'deleted_at' => null
]);
return !$result->isEmpty();
});
ここで利用しているよ
$section_ids->filter(function ($item, $key) use ($is_publish, $r_section_content) {
$result = $r_section_content->byWhere([
'section_id' => $item,
'is_publish' => $is_publish, // 公開済み
'deleted_at' => null
]);
return !$result->isEmpty();
});

