How to load only existing preload data in adonis js

1.5k Views Asked by At

I am working in adonis js I have a relation between my category table and my dishes table but when i preload dishes it loads dishes which have empty relation as well

    const data = await Category
    .query()
    .preload('dishes',(builder)=>{
      builder.where('user_id',request.input('user_id'));
    })
    .paginate(1,2);
{"status": 200,"message": "","data": {"meta": {"total": 2,"per_page": 2,"current_page": 1,"last_page": 1,"first_page": 1,"first_page_url": "/?page=1","last_page_url": "/?page=1","next_page_url": null,"previous_page_url": null},"data": [{"id": 1,"name": "Breakfast","status": 1,"created_at": null,"updated_at": null,"dishes": [{"id": 1,"user_id": 14,"category_id": 1,"type": 1,"name": "paneer butter masala","image": null,"description": "paneer","price": 120,"deliverytype": 0,"is_discounted": 0,"created_at": null,"updated_at": null},{"id": 2,"user_id": 14,"category_id": 1,"type": 2,"name": "chiken butter masala","image": null,"description": "chicken","price": 140,"deliverytype": 0,"is_discounted": 0,"created_at": null,"updated_at": null}]},{"id": 2,"name": "Category","status": 1,"created_at": null,"updated_at": null,"dishes": []}]}}

i want only those category which have relation with dishes

1

There are 1 best solutions below

0
On

ues the whereHas

eg.

const data = await Category
    .query()
    .whereHas('dishes', (query) => {
        // filter query

        query.where('user_id',request.input('user_id'))
   }).preload('dishes',(builder)=>{
        // pull the actual preload data

         builder.where('user_id',request.input('user_id'));
   }).paginate(1,2);

read more link below

https://docs.adonisjs.com/reference/orm/query-builder#wherehas