簡體   English   中英

三層雄辯的關系順序在Laravel 5中

[英]Three level eloquent relation orderBy in laravel 5

在我的數據庫中,有以下表格:

quotes
-id
-quote_title
...

quote_items
-id
-quote_id
-product_id

products
-id
-product_name
-product_category_d

我要實現的是使用product_category_id對查詢結果進行排序。

下面是查詢。

$query = Quote::query();
$query->whereHas('quote_item' , function ($query) {
    $query->whereHas('product' , function ($query) {
        $query->orderBy('product_category_id');
    });
 });
$temp= $query->find($id);

結果沒有顯示任何錯誤,但是順序不正確。

報價模型:

class Quote extends Model
{
    public function QuoteItem()
    {
        return $this->hasMany('app\QuoteItem');
    }
}

QuoteItem模型:

class QuoteItem extends Model
{
    public function Quote()
    {
        return $this->belongsTo('app\Quote');
    }

    public function Product()
    {
        return $this->belongsTo('app\Product');
    }
}

產品型號:

class Product extends Model
{
    public function QuoteItem()
    {
        return $this->hasMany('app\QuoteItem');
    }

}

我建議為Quote模型創建專用范圍:

public function scopeOrderByCategory($query)
{
    return $query
        ->join('quote_items', 'quote_items.quote_id', '=', 'quotes.id')
        ->join('products', 'products.id', '=', 'quote_items.product_id')
        ->orderBy('products.product_category_id');
}

然后,您可以在選擇報價並需要按其產品類別訂購它們時使用它:

$quotes = Quote::orderByCategory()->get();

但是,您必須對以下事實保持謹慎:該范圍內部將連接quote_itemsproducts表。

您可以在此處閱讀有關本地Eloquent范圍的更多信息

如果在查詢中仔細查看,則排序依據將放在whereHas子句中。 我認為應該放在with子句中

我這樣修改查詢。

$results = Quote::with(['QuoteItem' => function ($query) {
                            $query->join('products', 'products.id', 
                                         '=', 'quote_items.product_id')
                                  ->orderBy('product_category_id','ASC');
                        }])->whereHas('QuoteItem')->find($id);

使用Laravel的dd()函數顯示的結果: 在此處輸入圖片說明

暫無
暫無

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

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