[英]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_items
和products
表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.