在范围内使用模型的属性

时间:2019-10-14 17:10:20

标签: laravel eloquent

我已经在模型中定义了一个属性,并希望在范围内使用它。

protected $appends = ['lowest_price'];

public function getLowestPriceAttribute()
{
    $lowest_price = NULL;
    foreach($this->shops as $shop) {
        if(is_null($lowest_price)) { 
            $lowest_price = (double)$shop->pivot->price;
        }

        if($lowest_price > (double)$shop->pivot->price) {
            $lowest_price = (double)$shop->pivot->price;
        }
    }
    return $lowest_price;
}

我想在范围内使用的最低价格属性,但始终为'null':

public function scopeMaxPrice(Builder $query, $max_price): Builder {
    return $query->where('max_price', '>=', $this->lowest_price);
}

如果我dd();范围内的getLowestPriceAttribute函数也将返回“ null”。我认为我可以访问“最低价格”属性。

该属性可以成为查询的一部分吗?如果没有,是否有一个优雅的解决方案?

编辑:作用域在“产品”控制器中被调用:

public function index()
{
    $products = QueryBuilder::for(Product::class)
        ->allowedFilters(
            AllowedFilter::exact('type_id')->default('1'),
            AllowedFilter::scope('min_speed')->default(0),
            AllowedFilter::scope('min_range')-> default(0)
           # AllowedFilter::scope('max_price')-> default(999)
        )
        ->get();

    $types = DB::table('types')->pluck('name', 'id');
    return view('pages.home', compact('products', 'types'));
}

注意:我正在使用Spatie querybuilder

0 个答案:

没有答案