I have the following table in "Category" table.
id | name | parent_id |
---|---|---|
1 | student | NULL |
2 | teacher | NULL |
3 | math_student | 1 |
4 | science_student | 1 |
I have the following table in "Post" table.
id | name | category_id |
---|---|---|
1 | Ajay | 3 |
2 | Mohan | 3 |
Post.php file from Models
public function category(){
return $this->belongsTo(Category::class, 'category_id', 'id');
}
if I place the below code I am getting the name of 3rd id that is math_student.
$post->category->name
but I want to get the name of the parent_id of the category i.e. – "student"
I have tried the following code but it is wrong.
$post->category->parent_id->name
please suggest me the solution
2
Answers
Within the Category Model, add parent relationship:
Then, you can get the parent name
You need to set up a relationship using
parent_id
to find the model instance ofCategory
within itself.In the Category.php model:
After that, you will be able to: