0
votes

I have a product table and a category table and the category_product table. I want to get products of a specific category then run an other query on the retrieved products using a column that belongs to products table. for example all products that belongs to mobile category and have price less than 1000$. how can i do that? and second question: how to add pagination to it?

UPDATE: solved

with a query like this:

$products = Category::where(['title' => 'mobile'] )->first()->pictures()->where('price', '<' , 1000)->latest()->paginate(10);
1

1 Answers

0
votes

You have couple different options:

Category::whereTitle('mobile')->with(['pictures' => function ($q) {
  $q->where('price', '<' , 1000)->latest();
}])->paginate(10);

Or you can define scope inside of your Category model, something like

// @Category Model

public function cheapPictures() {
   return $this->hasMany(Picture::class)->where('price', '<' , 1000);
}

You can also use local scopes https://laravel.com/docs/5.6/eloquent#local-scopes