从类别 id laravel 中获取类别名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45193174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:20:12  来源:igfitidea点击:

Get category name from category id laravel

phplaravel

提问by Niju

I am very new to laravel and have two table one post table and one category table. I have only one category related to one post, so i add category id in post table.So now i want to display all post with category name.

我对 Laravel 很陌生,有两张表,一张是帖子表,一张是分类表。我只有一个与一篇帖子相关的类别,所以我在帖子表中添加了类别 ID。所以现在我想显示所有带有类别名称的帖子。

post table:id,name,category_id,status

发布表:id、name、category_id、status

category Table:id,name

类别表:id,name

i want to dispaly like POST NAME CATEGORY NAME

我想显示 POST NAME CATEGORY NAME

I have two model category and post, so how can i write the eloquent relationship or give me a simple way to get the array of post with category name

我有两个模型类别和帖子,那么我怎样才能写出雄辩的关系或给我一个简单的方法来获取带有类别名称的帖子数组

回答by Angad Dubey

In your Post model:

在您的 Post 模型中:

public function category() {
    return $this->belongsTo(Category::class);
}

Now it will be available to you from the Post model directly

现在它可以直接从 Post 模型中使用

$post = Post::find($id);

$category_name = $post->category->name;

Edit for question in comment:

编辑评论中的问题:

There are a number of ways you can get posts by category name, for easy of use I would do this:

您可以通过多种方式按类别名称获取帖子,为了便于使用,我会这样做:

In category model:

在类别模型中:

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

Now you have it available through the category model:

现在您可以通过类别模型使用它:

$category = Category::where('name', $name)->first();

$posts_collection = $category->posts()->get();

回答by haakym

On your Post model you can write the category relationship like this:

在您的 Post 模型上,您可以像这样编写类别关系:

public function category() {
    return $this->belongsTo(Category::class); // don't forget to add your full namespace
}

You can then do something like this...

然后你可以做这样的事情......

$posts = Post::with('category')->get();

which will get all your posts with the category it belongs to.

这将获得您所有的帖子及其所属类别。

You can then iterate over the $postsvariable, for example, using blade...

然后您可以迭代$posts变量,例如,使用刀片...

@foreach ($posts as $post)
    <tr>
        <td>{{ $post->name }}</td>
        <td>{{ $post->category->name }}</td>
    </tr>
@endforeach

Read up further here: https://laravel.com/docs/5.4/eloquent-relationships#defining-relationships

在这里进一步阅读:https: //laravel.com/docs/5.4/eloquent-relationships#defining-relationships