如果你已經有了集合,你可以使用filter()
方法基於模型的方法來篩選出結果:
$billboards = Billboard::all();
$filtered = $billboards->filter(function ($billboard, $key) {
// true to keep; false to remove
return $billboard->isDisplayable();
});
如果你想使用這個邏輯上查詢(前集合,甚至建立),您可以在您的Billboard
型號上創建查詢範圍:
public function scopeDisplayable($query, $displayable = true)
{
if ($displayable) {
// modify $query to only get displayable items, e.g:
$query->where('displayable', '=', 1);
} else {
// modify $query to only get non-displayable items, e.g:
$query->where('displayable', '=', 0);
}
}
// use your new query scope like any other method on the query builder:
// displayable billboards:
$billboards = Billboard::displayable()->get();
// non-displayable billboards:
$billboards = Billboard::displayable(false)->get();