【问题标题】:Eloquent how to pass parameters to relationship雄辩的如何将参数传递给关系
【发布时间】:2020-01-16 16:35:09
【问题描述】:

我正在尝试修复的代码如下所示。我有一个 Hotel 类,用于在查询中获取某个区域内的所有酒店,但它不会丢弃那些不可用的酒店。里面有一个方法应该是一个访问器,但它没有按照我预期的方式编写:

public function isAvailableInRanges($start_date,$end_date){

        $days = max(1,floor((strtotime($end_date) - strtotime($start_date)) / DAY_IN_SECONDS));

        if($this->default_state)
        {
            $notAvailableDates = $this->hotelDateClass::query()->where([
                ['start_date','>=',$start_date],
                ['end_date','<=',$end_date],
                ['active','0']
            ])->count('id');
            if($notAvailableDates) return false;

        }else{
            $availableDates = $this->hotelDateClass::query()->where([
                ['start_date','>=',$start_date],
                ['end_date','<=',$end_date],
                ['active','=',1]
            ])->count('id');
            if($availableDates <= $days) return false;
        }

        // Check Order
        $bookingInRanges = $this->bookingClass::getAcceptedBookingQuery($this->id,$this->type)->where([
            ['end_date','>=',$start_date],
            ['start_date','<=',$end_date],
        ])->count('id');

        if($bookingInRanges){
            return false;
        }

        return true;
    }

我想使用此查询过滤掉酒店。所以这是来自控制器的查询:

    $list = $model_hotel->with(['location','hasWishList','translations','termsByAttributeInListingPage'])->get();

是否可以将天数范围传递给函数?

顺便说一句,我尝试的第一件事是在查询之后使用集合并通过集合传递过滤器函数,然后手动分页,但虽然它确实过滤,但显然它丢失了 “Eloquent”结果集集合属性,它最终成为一个常规集合,因此它对我不起作用。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    也许最好的方法是创建一个查询范围 (source) 并将所有逻辑放入此函数中。

    之后,您可以调用此范围并传递日期。例如,您将创建一个查询范围并将代码粘贴到其中。

    public function scopeisAvailableInRanges($query, $start_date, $end_date) {
    }
    

    然后您将像这样在控制器中调用此查询范围。

    $list = $model_hotel::isavailableinranges($start_date, $end_date)->with(['location','hasWishList','translations','termsByAttributeInListingPage'])->get();
    

    请记住,在您的查询范围内,您将返回一个集合。您所有可用酒店的集合。

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多