簡體   English   中英

Laravel 5.7:雄辯的訂單通過相關模型以及使用whereHas條件

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

我有一個模型OptionGroup ,它具有一個相關的模型Option ,而后者又具有一個相關的模型Attribute

我想獲取所有帶有選項的OptionGroup,其中Option具有特定的屬性( product_id )值,然后在Attribute模型中對所有其他值進行排序( default )。

在我的控制器中:

$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();

我嘗試了各種雄辯的范圍,嘗試在模型上應用orderBy() ,但沒有成功。

謝謝。

下面的查詢會給你所有OptionGroups有至少一個Option它有一個Attribute屬於一個給定的產品(由所確定的product_id )。 然后,該查詢還將僅用給定的product_id加載所有Options及其Attributes 但是由於模棱兩可,無法對子關系進行排序:

$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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM