【发布时间】: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,因为目前您限制自己检索未批准的帖子。