Home  >  Q&A  >  body text

How to get parent_id name of category table from post table

I have the following table in the "Category" table.

id Name parent_id
1 student null
2 teacher null
3 MATHEMATICS STUDENT 1
4 Science Student 1

I have the following table in the "Release" table.

id Name category_id
1 阿杰 3
2 Mohan 3

Post.php file in model

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

If I put the following code, I will get the name of the third id which is math_student.

$post->category->name

But I want to get the name of the parent_id of the category, i.e. - "Student"

I tried the following code but got an error.

$post->category->parent_id->name

Please suggest me a solution

P粉936568533P粉936568533403 days ago547

reply all(2)I'll reply

  • P粉393030917

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

    In the category model, add a parent relationship:

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

    Then, you can get the parent name

    $post->category->parent->name

    reply
    0
  • P粉990008428

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

    You need to establish a relationship using parent_id to find the model instance for Category inside it.

    In the Category.php model:

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

    Afterwards, you will be able to:

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

    reply
    0
  • Cancelreply