【发布时间】:2018-09-19 21:53:03
【问题描述】:
我有三个模型 ProductCategory ,Product 和 ProductPrice 。我的模型是这样的
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