为了账号安全,请及时绑定邮箱和手机立即绑定

通过关系从类别id中获取类别名称

通过关系从类别id中获取类别名称

PHP
慕田峪9158850 2023-08-19 10:25:32
我浏览了论坛,但到目前为止我看到的解决方案与我遇到的问题不一致,因此,我希望有更了解情况的人能够提供帮助。所以我有一个类别调制解调器和一个后置模型,它们的关系如下;在帖子模型上:public function postcategory(){    return $this->belongsTo(PostCategory::class);}在类别模型上:public function posts(){    return $this->hasMany(Post::class)->where('approved', 'true');}我使用 slugs 来检索属于某个类别 slug 的所有帖子,使用以下函数:public function cats($category){    $posts = PostCategory::where('category_slug', $category)->first()->posts;    $category = PostCategory::where('category_slug', $category)->first();    return view('posts', compact('posts', 'category')); }现在,我试图获取帖子表中存储的类别 id 的类别名称。例如,如果我的类别 id 为 1,并且在类别表中,如果 id 号 1 是 PHP,那么如何返回名称 PHP 而不是 id 1?其次,如果我想对帖子被压缩的视图进行分页,我该怎么做?我将控制器中的代码切换为:$posts = PostCategory::with('posts')->where('category_slug', $category)->paginate(15);当我添加该行代码时,它返回一些值(带有关系),但是当我将其传递给视图时,我收到错误。希望有人看到这个并帮助我。:D
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

关于类别模型:


public function posts()

{

    return $this->hasMany(Post::class);

}

在控制器上:


public function cats($slug)

{

    $category = PostCategory::whereSlug($slug)->firstorFail();

    $posts= $category->posts()->where('approved', 'true')->paginate(15);

    return view('category.show', compact('posts', 'category'));

}

查看中:


@foreach($posts as $post)

 $post->title

 ....

@endforeach

{{ $posts->links() }}


查看完整回答
反对 回复 2023-08-19
  • 1 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信