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
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
You need to establish a relationship using
parent_idto find the model instance forCategoryinside it.In the Category.php model:
public function parent(){ return $this->belongsTo(Category::class, 'parent_id', 'id'); }Afterwards, you will be able to: