簡體   English   中英

如何過濾laravel中的關系屬性

[英]how to filter the relationship attributes in laravel

嗨,我有一個名為room的 model 和另一個名為 roomAttribute 的roomAttribute在房間屬性中我有價格和大小字段現在我想按價格過濾房間,當我發送價格時,我只想顯示價格范圍內的屬性,但是當我使用 whereHas或者當條件成真時,兩者都會給我帶來所有屬性,所以這就是我嘗試過的,我想要的:

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

另一個嘗試是

     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);
        });

所以在我的數據庫中考慮我有 3 行:

"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,

                }
            ]

所以當我向這個 api 發送價格時,start_price 為 100,結束價格為 200,我只想顯示前兩項屬性而不是第三項,我該如何實現?

您的查詢:

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);
    });

表示價格必須大於起始價格且小於最終價格,但絕不等於。 您想更改查詢以檢查“大於或等於”和“小於或等於”:

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);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM