Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afoysal's avatar

Using hasMany()

I have three table Product, Model and Variant. Product has many Model. Model has many Variant. There is product_id in Model table. There are product_id and model_id in Variant table.

How can I use hasMany() in Model model class to fetch Products along with Model and Variant in Product controller?

0 likes
4 replies
christianyeah's avatar

does variant belongs to model, which means one model has many variant.

in this case, depends on the name of the functions

# in Product class
public function models()
{
    return $this->hasMany('Model');
}
# in Model class
public function variants()
{
    return $this->hasMany('Variant');
}
# to find the product's models and its models variants, like
Product::with('models','models.variants')->find(1)
1 like
staudenmeir's avatar

You can also combine two HasMany relationships into a HasManyThrough:

public function variants() {
    return $this->hasManyThrough(Variant::class, Model::class);
}
1 like
afoysal's avatar

Thanks @christianyeah for your reply. Can I get result like below from your solution ? Thanks @staudenmir Thanks @Vilfago

Product1 
    --Model 1   
        --Variant1
    --Model2
        --Variant1
        --Variant2
        --Variant3

Product2
    --Model1
        --Variant1
        --Variant2

Thanks.

Please or to participate in this conversation.