Laravel - how to use model's ID inside belongs to many relationship query?

Viewed 194

Models:

Products
Variants
VariantValue

// Product.php
public function variants()
{
    return $this->belongsToMany(Variant::class, 'product_variant', 'product_id', 'variant_id')
        ->with([
            'values' => function ($builder) {
                return $builder->whereHas('products', function ($q) {
                    return $q->where('products.id', $this->id);
                });
            },
        ]);
}


// Variant.php
public function values()
{
    return $this->hasMany(VariantValue::class);
}


// VariantValue.php
public function products()
{
    return $this->belongsToMany(Product::class, 'product_variant_value', 'variant_value_id', 'product_id');
}

The above works if we do the following:

Product::first()->variants()->get()->toArray()

But, it doe NOT work if we do the following (the values array is empty):

Product::with('variants')->get()->toArray()

Meaning the issue is that the product ID is not available inside the belongs to many query:

return $q->where('products.id', $this->id);

Any idea how I can make this work? The goal is to load relationship using:

Product::with('variants')->get()
0 Answers
Related