3 回答

TA貢獻1804條經驗 獲得超8個贊
您可以從數據庫中獲取數據,然后按照您想要的方式對它們進行分組:
$posts = Post::with('categories')->get();
$result = $posts->groupBy([
'categories',
function ($item) {
return $item['category_name'];
},
], $preserveKeys = true);
有關按關系字段分組的更多詳細信息:
https://laravel.com/docs/7.x/collections#method-groupby

TA貢獻1840條經驗 獲得超5個贊
根據給定的表:posts 和 categories 表是主表,category_post 表是一個數據透視表,其中包含 posts 和 categories 表之間的關系:
所以,你的關系應該是 posts->category_post->categories
$posts = Posts::with('category_post')->get();
$grouped = $posts->groupBy('category_post.category_id');
category_post 還與類別數據的類別表相關。

TA貢獻1895條經驗 獲得超7個贊
belongsToMany在類別模型中,您可以像下面這樣設置和關系
function posts()
{
? ?return $this->beongsToMany(Post::class, 'category_post', 'category_id', 'post_id');
}
- 3 回答
- 0 關注
- 156 瀏覽
添加回答
舉報