从类别ID laravel获取类别名称 [英] Get category name from category id laravel

查看:383
本文介绍了从类别ID laravel获取类别名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对laravel很陌生,有两个表,一个表,一个表.我只有一个与一个帖子相关的类别,因此我在帖子表中添加了类别ID.所以现在我要显示所有带有类别名称的帖子.

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.

帖子表: id,名称,category_id,状态

post table: id,name,category_id,status

类别表: ID,名称

我想像 职位名称 类别名称

i want to dispaly like 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

推荐答案

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

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

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.

然后您可以遍历$posts变量,例如,使用blade ...

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

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

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

这篇关于从类别ID laravel获取类别名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆