Home > database >  Has many through self referencing in laravel returns empty set
Has many through self referencing in laravel returns empty set

Time:10-02

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 retireve 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

CodePudding user response:

1- this kind of relation is not necessary. because parent product and children products have one-to-many relations not many-to-many.

2- hasManyThrough get destination class address not self::class.(like: ChildProduct::class)

CodePudding user response:

You are looking for a many-to-many with a pivot table:

public function childs(){
    return $this->belongsToMany(self::class, 'product_relations', 'parent_product_id', 'child_product_id');

    }
  • Related