【问题标题】:How to order results of related models in laravel?如何在laravel中对相关模型的结果进行排序?
【发布时间】:2018-09-19 21:53:03
【问题描述】:

我有三个模型 ProductCategoryProductProductPrice 。我的模型是这样的

ProductCategory.php

  public function product()
    {
        return $this->belongsTo('App\Models\Product');
    }
  public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

而我的产品模型是这样的

 public function category()
    {
        return $this->hasOne('App\Models\ProductCategory');
    }

    public function price(){
       return $this->hasMany('App\Models\ProductPrice');
    }

现在我想获取一个类别的所有产品,并按要求按name/price 对它们进行排序。我的查询是

        $query = ProductCategory::with(['product'=>function($q){
          $q->whereHas('price',function ($q){
              $q->where('quantity','>',0);
              $q->where('status',1);
          });

        }])->whereHas('category',function ($q) use ($cat){
            $q->where('category_slug',$cat);
        });

switch ($request->get('sort')){
                case 'price':
             $query->product()->price()->orderBy('amount','asc');
                    break;
                case 'name':
                        $query->product()->orderBy('title','asc');
                    break;

            }
  $data['result']=$query->paginate(30)->toArray();

所以我期待这个查询会从类别中返回我的产品,并根据要求按price or name 对它们进行排序。但不是那样,而是给我错误的说法

Call to undefined method Illuminate\Database\Query\Builder::product()

我已经关注了这些帖子,但没有帮助

Laravel orderBy on a relationship

Laravel Eloquent: How to order results of related models?

https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship

还有一些我发现与我的问题很接近。谁能帮我查询一下谢谢

【问题讨论】:

  • 您需要在数据库查询结束时使用->first()->get(),否则它不会获取任何信息。
  • 对不起,我会更新问题
  • 在switch语句前添加此行$query = $query->first()
  • 这给了我结果,但没有给出关系表的数据。它只提供来自 ProductCategory 模型的数据
  • 您的数据模型似乎有点不对劲。为什么您在 Product to ProductCategory 上有一个 hasOne 但 ProductCategory 属于产品和类别?我假设您的 ProductCategory 表如下所示:id| product_id | category_id ?如果是这种情况,将category_id 直接放在产品表中是有意义的

标签: php laravel laravel-5 eloquent


【解决方案1】:

我发现这个问题不能这样解决。要解决这个问题,需要另一种方法。

我就是这样做的。

$query = Product::with('sizes','images')->whereHas('productCategory',function ($q) use ($cat,$request,$cate){
            $q->whereHas('category',function ($q) use ($cat ,$request,$cate){
               $q->where('category_slug',$cat);

            });

        });
        $data['result']=$query->get()->toArray();

这很容易排序

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 2014-10-31
    • 2021-02-10
    • 2019-03-15
    • 1970-01-01
    • 2020-07-19
    • 2012-01-28
    • 2015-08-10
    • 2020-09-03
    相关资源
    最近更新 更多