首页  >  问答  >  正文

如何从post表中获取类别表的parent_id名称

我在“类别”表中有下表。

id 姓名 parent_id
1 学生
2 老师
3 数学学生 1
4 科学学生 1

我在“发布”表中有下表。

id 姓名 category_id
1 阿杰 3
2 莫汉 3

模型中的 Post.php 文件

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

如果我放置以下代码,我将获得第三个 id 的名称,即 math_student。

$post->category->name

但我想获取该类别的parent_id的名称,即-“学生

我尝试了以下代码,但错误。

$post->category->parent_id->name

请给我建议解决方案

P粉936568533P粉936568533403 天前544

全部回复(2)我来回复

  • P粉393030917

    P粉3930309172023-09-13 10:28:10

    在类别模型中,添加父关系:

    public function parent(){
            return $this->belongsTo(Category::class, 'parent_id', 'id')->withDefault();
        }

    然后,就可以获取父名称

    $post->category->parent->name

    回复
    0
  • P粉990008428

    P粉9900084282023-09-13 00:59:29

    您需要使用 parent_id 建立关系,以在其内部查找 Category 的模型实例。

    在 Category.php 模型中:

    public function parent(){
        return $this->belongsTo(Category::class, 'parent_id', 'id');
    }
    

    之后,您将能够:

    $post->category->parent->name;
    

    回复
    0
  • 取消回复