Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ankush981's avatar

I need to get those products who have men category. How can i get only men category products.


Im having 3 tables.

1- products
2- category_products
3- categories

table: products: 

	fields: id ,
	 	product_name

table: category_products: 
		fields: id ,category_id, product_id

table: categories: 
		fields: id , category_name

I need to get those products who have men category. How can i get only men category products.



  $products = Product::with(['categories' => function($q){
			$q->with(['categoryNames' => function($q){
				$q->select('*');

			}])
			->select('*');
		}])
		->select('id_product','parent_id', 'name', 'price', 'selling_price', 'image', 'discount')
		->where('parent_id', 0)
		->get();

0 likes
4 replies
forrestedw's avatar

I would go with:

$productQuery->whereHas('categories', function($query) {
		$query->where('name', '=', 'men');
})
ankush981's avatar

@forrestedw  thanks your reply 

$products = Product::with(['categories' => function($q){
			$q->with(['categoryNames' => function($q){
				$q->select('*');

			}])
			->select('*');
		}])
		->select('id_product','parent_id', 'name', 'price', 'selling_price', 'image', 'discount')
		->where('parent_id', 0)
		->get();
// i need to put after this

$products->whereHas('categories', function($query) {
		$query->where('name', '=', 'men');
});

// categoryNames relation has name not categories relation
or how ?

forrestedw's avatar

I'm not sure I fully understand what you are asking, but you can nest the query in the same way to get to deeper relationships, like this:

$productQuery->whereHas('categories', function($query) {
        $query->whereHas('categoryName', function ($query) {
				$query->where('name', '=', 'men');
         });
})

Please or to participate in this conversation.