首页 > 解决方案 > laravel 5中的三级雄辩关系orderBy

问题描述

在我的数据库中,我有以下表格:

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');
    }
}

报价单型号:

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');
    }

}

标签: phplaravellaravel-5eloquentlaravel-5.4

解决方案


我建议为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表的事实保持谨慎。

您可以在此处阅读有关本地 Eloquent 作用域的更多信息。


推荐阅读