简体   繁体   English

Laravel 6 groupBy到belongsTo关系

[英]Laravel 6 groupBy to belongsTo relationship

Hello I have Post model with relation:您好,我有 Post 模型与关系:

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

I need show posts on every tab of category.我需要在每个类别的标签上显示帖子。 For this I need use groupBy.为此,我需要使用 groupBy。 When I do this:当我这样做时:

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

I get error:我得到错误:

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

Why?为什么? How I can return my posts with key of category title?如何使用类别标题的键返回我的帖子?

For multilangual I use this package: https://github.com/spatie/laravel-translatable对于多语言我使用这个包: https : //github.com/spatie/laravel-translatable

Try Collection's group-by method:试试Collection 的 group-by方法:

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

You may pass a callback to return the value you wish to key the group by (as you mentioned you are using laravel-translatable package):您可以传递一个回调来返回您希望作为组键的值(正如您提到的,您正在使用 laravel-translatable 包):

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

You can use something like this:你可以使用这样的东西:

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

and then in blade files you can foreach tabs and find a name by category_id然后在刀片文件中,您可以 foreach 选项卡并按 category_id 查找名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM