【问题标题】:Get category name from category id through relationship. Laravel通过关系从类别 id 获取类别名称。拉拉维尔
【发布时间】:2020-11-11 13:04:03
【问题描述】:

我浏览了论坛,但到目前为止我看到的解决方案与我遇到的问题不符,所以我希望更知情的人能提供帮助。

所以我有一个Category modem和A post model,关系如下;

关于后期模型:

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);

当我 dd 那行代码时,它返回一些值(带有关系),但是当我将它传递给视图时,我得到了错误。

希望有人看到这个并帮助我。 :D

【问题讨论】:

  • "when I pass that to the view, I get errors."。错误是什么?
  • 如果视图失败,请包含视图
  • 嗨,cyberkid,您需要提供更多关于视图中显示的错误的信息。此外,您可能想从 posts 函数中删除 where('approved', true) ,然后将其添加为范围方法。如果您真的想在模型上使用这样的方法,则将其命名为approvedPosts,因为目前您限制自己检索未批准的帖子。

标签: php laravel eloquent


【解决方案1】:

关于类别模型:

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() }}

【讨论】:

  • 嗨 xNoJustice, OP 的 posts 函数实现比你的 getPosts 函数更干净。然后,他可以使用范围来拉入已批准的职位。也不需要使用 WhereId 函数,因为 find 更干净并且做同样的事情。但如果使用良好的关系管理,则无论如何都不需要这样做。
  • 如果我做对了,我就修好了。你会再看一遍吗? @ColinMD
  • 你现在有了关系,但你不应该对关系方法进行额外的查询,如果 OP 想要所有未批准的帖子,或者想要对 30 个结果进行分页或不排序,会发生什么,因为该逻辑编码在您无法执行的关系函数上。因此,hasMany 之后的所有内容都应该被删除,首先是像 scopeApproved() 这样的作用域方法,然后可以在需要时将 orderBy 和 paginate 添加到控制器中。
  • 你是对的。但他想在那之前的那个问题。这不是第一个问题。如果你看看她的老问题,你就可以理解我为什么这样做了。
  • 根据我对 OP 的评论,要做到这一点,您需要将其称为approvedPosts 而不是帖子。如果你看昨天的问题,正确的答案是叫它approvedPosts。 'posts' 的关系应该只是将关系返回到 Post' 模型,并且任何进一步的查询都应该在关系方法之后进行限定或添加。关于 orderBy 和分页,我认为在控制器中执行此操作总是更好,假设用户需要实现一个 api 调用并每次调用返回 300 个帖子,它不能在给定的实现中完成..
猜你喜欢
  • 2017-08-10
  • 2017-12-24
  • 2020-12-19
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 2020-12-06
  • 1970-01-01
相关资源
最近更新 更多