I have three model ProductCategory
,Product
and ProductPrice
. My models are like this
ProductCategory.php
public function product()
{
return $this->belongsTo('App\Models\Product');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
And my Product model is like this
public function category()
{
return $this->hasOne('App\Models\ProductCategory');
}
public function price(){
return $this->hasMany('App\Models\ProductPrice');
}
Now i want get all the product of a category and sort them by name/price
as requested. My query for this is
$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();
So i was expecting that this query will return me product from the category and will sort them by price or name
as requested. But instead of that its giving me error saying
Call to undefined method Illuminate\Database\Query\Builder::product()
I have followed these threads but no help
Laravel orderBy on a relationship
Laravel Eloquent: How to order results of related models?
https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship
And few more these are the one i found to be close to my problem. Can anyone please help me with the query Thanks