简体   繁体   English

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

[英]Get category name from category id through relationship. Laravel

I have looked through the forum, but the solutions I have seen so far, aren't aligning with the issues I'm getting, so, I was hoping someone more informed would help out.我浏览了论坛,但到目前为止我看到的解决方案与我遇到的问题不符,所以,我希望更知情的人能提供帮助。

So I have a Category modem and A post model and there relationship is as follows;所以我有一个Category modem和A post model,关系如下;

on post model:在 model 后:

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

on category model:在 model 类别上:

public function posts(){
    return $this->hasMany(Post::class)->where('approved', 'true');
}

and I am using slugs to retrieve all the posts that belongs to a certain category slug, using this function:我正在使用 slugs 检索属于某个类别 slug 的所有帖子,使用这个 function:

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

Now, I am trying to get the name of the category with the category id stored in the posts table.现在,我正在尝试使用存储在帖子表中的类别 ID 获取类别的名称。 for example, if I have a category id of 1 and on the category table, if the id number 1 is PHP, how do I return the name PHP instead of the id 1?例如,如果我的类别 id 为 1,并且在类别表上,如果 id 编号 1 是 PHP,我如何返回名称 PHP 而不是 id 1?

Secondly, if I wanted to paginate the view where posts is being compacted to, how do I do that?其次,如果我想对帖子被压缩到的视图进行分页,我该怎么做? I switched the code in the controller to this:我将 controller 中的代码切换为:

$posts = PostCategory::with('posts')->where('category_slug', $category)->paginate(15);

when I dd that line of code, it returns some values (with relations), but when I pass that to the view, I get errors.当我 dd 那行代码时,它返回一些值(带有关系),但是当我将它传递给视图时,我得到了错误。

Hopefully, someone see this and help me out.希望有人看到这一点并帮助我。 :D :D

on Category Model:在类别 Model 上:

public function posts()
{
    return $this->hasMany(Post::class);
}

On Controller:在 Controller 上:

public function cats($slug)
{
    $category = PostCategory::whereSlug($slug)->firstorFail();
    $posts= $category->posts()->where('approved', 'true')->paginate(15);
    return view('category.show', compact('posts', 'category'));
}

On View:在视图中:

@foreach($posts as $post)
 $post->title
 ....
@endforeach
{{ $posts->links() }}

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

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