Y
Y
Yevhenii K2021-02-24 16:27:33
Laravel
Yevhenii K, 2021-02-24 16:27:33

What are custom pivot models for?

Wanted to use it to "Eager Load" additional Many-to-Many relationships, but it doesn't work.
60362322a3fd4040947558.png
Why are they needed in practice?

class Product extends Model
{
    public function features(): BelongsToMany
    {
        return $this->belongsToMany(Feature::class, 'feature_product_pivot')
            ->using(ProductFeature::class)
            ->withPivot(['value_id', 'unit_id']);
    }
}
class ProductFeature extends Pivot
{
    protected $table = 'feature_product_pivot';
    protected $with = ['value', 'units'];

    public function value()
    {
        return $this->belongsTo(FeatureValue::class, 'value_id', 'id');
    }

    public function unit()
    {
        return $this->belongsTo(FeatureUnit::class, 'unit_id', 'id');
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question