orderBy on hasMany Relationship laravel

问题描述 投票:0回答:2

我使用ProductCatRel模型建立了从类别模型到产品模型的“ hasMany”关系。

我正在尝试通过类别模型订购产品。 “ where”条件很好,但是“ orderBy”不起作用。这是我的代码:

public function Products(){
    return $this->hasMany(ProductCatRel::class,'category')
        ->with('Product')
        ->whereHas('Product', function($q){
            $q->where('status', 1)->orderBy('position');
    });
}
laravel relationship has-many
2个回答
0
投票

使用以下代码段可能会起作用

public function products(){
    return $this->hasMany(ProductCatRel::class,'category')
        ->with('Product')
        ->whereHas('Product', function($q){
            $q->where('status', 1)
    });
}

$products = App\Category::find(1)->products()->orderBy('position')->get();

0
投票

[whereHas()仅检查是否存在,不影响检索到的关系数据。

您应该以orderBy()方法应用with()。另外,您需要在with()方法中重复状态检查。

public function Products(){
    return $this
        ->hasMany(ProductCatRel::class, 'category')
        ->with(['Product' => function ($q) {
            $q->where('status', 1)->orderBy('position');
        }])
        ->whereHas('Product', function($q) {
            $q->where('status', 1);
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.