Hi I'm new to laravel (eloquent). I'm trying to make one to one through (level/tree) relationship using eloquent ORM. I have product_category
table that have id
and parent_id
.
This is my product_category
table
|-----|--------|-----------|
| id | name | parent_id |
|-----|--------|-----------|
| 1 | book | 0 |
| 2 |notebook| 1 |
This is my product
table
|----|----------------|-------------|
| id | name | category_id |
|----|----------------|-------------|
| 1 | super notebook | 2 |
I want to be able to pull parent category information from subcategory_id info in product alone. Is this possible?
When using SQL, this is the query (assume category_id
is 2)
SELECT * FROM `product_category` WHERE `id` = (SELECT `parent_id` FROM `product_category` WHERE `id` = '2' )
Update:
This is my current implementation
<?php
class Product extends Eloquent {
public function subcategory()
{
return $this->hasOne('ProductCategory');
}
public function category()
{
// This should get the parent info of the subcategory
return ProductCategory::find($this->subcategory->parent_id);
}
}