简体   繁体   中英

how to filter the relationship attributes in laravel

hi i have a model called room and another model called roomAttribute in room attribute i have price and size fields now i want to filter the rooms by price and when i send price i just want to show the attributes in price range but when i use whereHas or with it boths brings me all attributes when the condition comes true so here is what i tried and i want:

   return $query->with([
            'attributes' => function (Builder $q) use ($start_price,$end_price) {
            $q->where('price', '>',$start_price);
            $q->where('price', '<',$end_price);
            }
        ]);

and another try was

     return $query->whereHas('attributes', function (Builder $q) use ($start_price,$end_price) {
            $q->select('price');
            $q->where('price', '>',$start_price);
           $q->where('price', '<',$end_price);
        });

so in my db consider i have 3 rows:

"id": 1,
            "name": "test",
            "description": "test",
            "Attributes": [
                {
                    "id": 1,
                    "room_id": 1,
                    "size": 20,
                    "price": 200,
                },
                {
                    "id": 2,
                    "room_id": 1,
                    "size": 20,
                    "price": 200,
                },
                {
                    "id": 3,
                    "room_id": 1,
                    "size": 55,
                    "price": 25000,

                }
            ]

so when i send price to this api with start_price of 100 and end price of 200 i just want to show the first 2 items of attributes and not the third one how can i achieve that??

Your query here:

return $query->whereHas('attributes', function (Builder $q) use ($start_price,$end_price) {
        $q->select('price');
        $q->where('price', '>',$start_price);
       $q->where('price', '<',$end_price);
    });

Says that the price has to be greater than the start price and less than the end price, but never equal. You want to change the query to check for "greater than or equal" and "less than or equal":

return $query->whereHas('attributes', function (Builder $q) use ($start_price,$end_price) {
        $q->select('price');
        $q->where('price', '>=',$start_price);
       $q->where('price', '<=',$end_price);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM