0
votes

i wanna use multiple hasMany and belongsTo that subcategory uses two function, onece for return products and another once for return products with orderBy condition. how can i do that????

class Category extends Eloquent{
   public function product(){
      return $this->hasMany('Product');  
   }
   public function product_ordered(){
      return $this->hasMany('product')->orderBy('updated_at','DESC');
   }
}

and Product file:

class Product extends Eloquent{
   public function Category(){
      return $this->belongsTo('category');
   }
}

and i wanna to use both of that in different Views

view 1:

@foreach($category->product_ordered as $x){
   ...
}

view2:

@foreach($category->product as $x){
   ...
}

Thank you so much...

1
And what's not working with the above code? - jedrzej.kurylo
return $this->hasMany('product')->orderBy('updated_at', 'DESC'); as the argument is the name of your model class (Product), make first character uppercase - Hayk Aghabekyan
i can not use same together... - Farshid

1 Answers

1
votes

You do not need to define the relation twice, you can make a method that accesses the first relation, then sorts it by whatever you need.

class Category extends Eloquent
{
   public function product(){
      return $this->hasMany('Product');  
   }

   public function product_ordered(){
      return $this->product->sortByDesc('updatedAt');
   }

}