Chris J
Chris J

Reputation: 562

Laravel 5.7: Eloquent orderBy related model as well as using whereHas condition

I have a model OptionGroup that has a related model Option which, in turn has a related model Attribute.

I'd like to get all the OptionGroups with their Options where the Option has a particular attribute (product_id) value and then order everything another value (default) within the Attribute model.

In my controller:

$optionGroups = OptionGroup::with(['options' => function($query) use ($product) {
            $query->whereHas('attributes', function($q) use ($product) {
                $q->where('product_id', $product->id);

                // Ideally here:
                // $q->orderBy('default', 'desc');
            });
        }])
        ->orderBy('sort_order', 'desc')
        ->get();

I've tried various eloquent scopes to try and apply the orderBy() on the model but without success.

Thanks.

Upvotes: 2

Views: 284

Answers (1)

Namoshek
Namoshek

Reputation: 6544

The following query will give you all OptionGroups that have at least one Option which has an Attribute that belongs to a given product (determined by the product_id). The query will then also only egaer load all Options and their Attributes with the given product_id. But sorting on a child relation is not possible due to ambiguity:

$optionGroups = OptionGroup::query()
    ->whereHas('options.attribute' => function ($query) use ($product) {
        $query->where('product_id', $product->id);
    })
    ->with(['options.attribute' => function ($query) use ($product) {
        $query->where('product_id', $product->id);
    }])
    ->get();

Upvotes: 1

Related Questions