【问题标题】:orderBy on hasMany relationship laravelorderBy on hasMany 关系 laravel
【发布时间】:2020-03-25 18:29:30
【问题描述】:

我使用 ProductCatRel 模型建立了从 Category 模型到 Product 模型的“hasMany”关系。

我正在尝试从 Category 模型订购我的产品。 “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


    【解决方案1】:

    使用下面的 sn -p 可能会起作用

    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();
    

    【讨论】:

      【解决方案2】:

      whereHas() 只检查存在,不影响检索到的关系数据。

      您应该在with() 方法中应用orderBy()。您还需要在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);
              });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-01
        • 2013-08-11
        • 2020-10-02
        • 2019-03-04
        • 2021-12-14
        • 2021-03-22
        • 2021-09-24
        • 2016-03-17
        相关资源
        最近更新 更多