簡體   English   中英

Laravel 6 groupBy到belongsTo關系

[英]Laravel 6 groupBy to belongsTo relationship

您好,我有 Post 模型與關系:

public function category()
{
    return $this->belongsTo(category::class);
}

我需要在每個類別的標簽上顯示帖子。 為此,我需要使用 groupBy。 當我這樣做時:

$posts = Post::with('category')->groupBy('category.title')->get();

我得到錯誤:

Column not found: 1054 Unknown column 'category.title'.

為什么? 如何使用類別標題的鍵返回我的帖子?

對於多語言我使用這個包: https : //github.com/spatie/laravel-translatable

試試Collection 的 group-by方法:

$posts = Post::with('category')->get()->groupBy('category.title')->all();

您可以傳遞一個回調來返回您希望作為組鍵的值(正如您提到的,您正在使用 laravel-translatable 包):

$posts = Post::with('category')->get()->groupBy(function ($post, $key) {
    return $post->category->getTranslation('title', 'fr');
})->all();

你可以使用這樣的東西:

$posts = Post::all()->groupBy('category_id')->get();

然后在刀片文件中,您可以 foreach 選項卡並按 category_id 查找名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM