How to filter data using the eager loading concept

#1

Hi, currently Im making a query to get all products and it’s categories associated


const data = await Product.query()
                              .with('categories')
                              .fetch()

And Im getting this result

image

The problem?

I want to get only the products with a category o multiple categories associated, so how could be my query?

I mean in my result I need to exclude the increible product and only show jabon y aceite

By the way Im working with a belongsToMany() relationship

0 Likes

#2
const data = await Product
  .query()
  .with('categories')
  .whereNotNull('categories')
  .fetch()
0 Likes

#3

no, it shows me an error that says

select * from products where categories is not null - ER_BAD_FIELD_ERROR: Unknown column ‘categories’ in ‘where clause’

I have three tables

products

categories

product_category

and only product_category table has the foreign keys of the two tables: product and category

But my question goes about if I insert a new product but this one is not registered in the pivot table, how can I exclude it from the resulset?

1 Like

#4

Indeed, that is a good question and I will face it too in one week or two.

0 Likes