How to get parent_id name of category table from post table
P粉936568533
P粉936568533 2023-09-12 22:21:06
0
2
584

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粉936568533
P粉936568533

reply all(2)
P粉393030917

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
P粉990008428

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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template