Christian Wagner
Christian Wagner

Reputation: 60

Laravel relation withAggregate

I am trying to order related Models by a custom column of a nested relation

I have these Models

Product with productDefaultSpecs, which is a hasMany(ProductDefaultSpec::class) relation

ProductDefaultSpec with productSpecType, which is a belongsTo(ProductSpecType::class) relation

ProductSpecType has a order_value (int) field

I achived some expected behaviour with this relation

public function productDefaultSpecs()
{
    return $this->hasMany(ProductSpec::class)
        ->withAggregate('productSpecType', 'order_value')
        ->orderBy('product_spec_type_order_value', 'DESC');
}

When I retrieve Products from the DB, the ProductDefaultSpec are ordered as expected.

But when I try to use e.g. $product->productDefaultSpecs()->delete() I get a SQL Error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_spec_type_order_value' in 'order clause'

Where is the mistake? Or is there a better way to get custom ordered related models?

Upvotes: 0

Views: 660

Answers (0)

Related Questions