[英]Get the limited items of each type grouped items laravel
我有一個名為books
的表和另一個名為categories
的表,它具有item_id, type, and others..
categories
中的列和 enum 中的type
enum (1/2/3)
現在我正在嘗試獲取每個組的有限項目,例如每種類型的 3 個項目所以為此我試圖獲得 9 個類別 3 每個具有不同類型
像這樣
Illuminate\Database\Eloquent\Collection {#2067 ▼
#items: array:3 [▼
1 => Illuminate\Database\Eloquent\Collection {#2060 ▼
#items: array:3 [▶]
}
2 => Illuminate\Database\Eloquent\Collection {#2055 ▼
#items: array:3 [▶]
}
3 => Illuminate\Database\Eloquent\Collection {#2026 ▼
#items: array:3 [▶]
}
]
}
到目前為止,我已經嘗試過。
$categoryLists = Category::where('display_at_home', 1)->limit(3)->get()->grouBy('type');
但它沒有做這項工作
您可以使用Eloquent Eager Limit package,如下所示。
class Book extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
...
}
class Category extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
...
}
然后要獲得您想要的關系,您可以執行以下操作:
$categoryLists = Category::where('display_at_home', 1)
->limit(3)
->with(['books' => function($query) {
$query->limit('3');
}])
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.