I'm using laravel v8 and i have a products
table to hold a product data, the product will have a child product and i'm connecting it using product_relations
table.
products
table:
id | name |
---|---|
1 | PC |
2 | Mouse |
3 | VGA |
product_relations
table
id | parent_product_id | child_product_id |
---|---|---|
1 | 1 | 2 |
2 | 1 | 3 |
I want to retrieve the child product model using the parent product model, to achieve this I'm trying to use hasManyThrough
function in class model like this;
class Product extends Model{
protected $primaryKey = 'id';
protected $table = 'products';
public function childs(){
return $this->hasManyThrough(self::class, ProductRelation::class, 'child_product_id', 'id');
}
}
class ProductRelation extends Model{
protected $primaryKey = 'id';
protected $table = 'product_relations';
}
then i tried to retrieve it like this:
$childs = Product::find(1)->childs()->get();
but it returns an empty set of product model