我已经浏览了论坛,但到目前为止,我看到的解决方案与我得到的问题不一致,所以,我希望有更多消息灵通的人来帮助我。
所以我有一个类别调制解调器和一个post模型,它们的关系如下所示;
在post模型上:
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'));
}
现在,我正在尝试使用存储在posts表中的类别id来获取类别的名称。例如,如果我有一个类别id为1,并且在category表上,如果id数字1是PHP,我如何返回名称PHP而不是id 1?
其次,如果我想对文章被压缩到的视图进行分页,我该怎么做呢?我将控制器中的代码切换为:
$posts = PostCategory::with('posts')->where('category_slug', $category)->paginate(15);
当我dd这行代码时,它返回一些值(带有关系),但是当我把它传递给视图时,我得到了错误。
希望有人能看到这一点并帮助我。:D
发布于 2020-07-22 09:38:45
关于类别模型:
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() }}
https://stackoverflow.com/questions/63026556
复制