三层雄辩的关系顺序在Laravel 5中

时间:2019-01-03 08:31:18

标签: php laravel laravel-5 eloquent laravel-5.4

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

from datetime import datetime

matched_string = "2020"
past = datetime.strptime(matched_string, "%Y")
present = datetime.now()

print(past.date() < present.date())

我想要实现的是使用product_category_id对查询结果进行排序。

下面是查询。

quotes
-id
-quote_title
...

quote_items
-id
-quote_id
-product_id

products
-id
-product_name
-product_category_d

结果不显示任何错误,但顺序不正确。

报价模型:

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

QuoteItem模型:

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

2 个答案:

答案 0 :(得分:3)

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

您可以阅读有关本地口才范围here的更多信息。

答案 1 :(得分:-2)

如果您在查询中仔细查看,则排序依据放在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()函数显示的结果: enter image description here