简体   繁体   English

Laravel 范围是否适用于每个模型实例?

[英]Does laravel scope works for every model instance?

I am using Laravel 5.7 and PHP 7.2.10.我使用的是 Laravel 5.7 和 PHP 7.2.10。

I want those records, for which either max_age = 0 or if max_age > 0, then it should check if given $age is in between max_age and min_age .我想要那些 max_age = 0 或 max_age > 0 的记录,那么它应该检查给定的$age是否在max_agemin_age之间。

In CarPremium modelCarPremium模型中

public function scopeAge($query, $age)
 {
     if ( $this->max_age == 0 ) {
        return $query;
     } else {
       return $query->where('min_age', '<=', $age)->where('max_age', '>=', $age)->orWhere('max_age','=',0);
    }
}

I am getting the records for which age not between max_age and min_age and not getting records for which max_age = 0 .我正在获取年龄不在max_agemin_age之间的记录,并且没有获取max_age = 0记录。

In tinker修补匠

>>> App\Models\CarPremium::query()->age(18)->get()
=> Illuminate\Database\Eloquent\Collection {#3064
     all: [
       App\Models\CarPremium {#3063
         id: 2,
         min_age: 25,
         max_age: 100,
         status: 1,
         created_at: "2018-12-10 05:34:39",
         updated_at: "2018-12-10 05:34:39",
       },
       App\Models\CarPremium {#3064
         id: 8,
         min_age: 18,
         max_age: 30,
         status: 1,
         created_at: "2018-12-10 05:34:39",
         updated_at: "2019-01-15 09:14:53",
       },
     ],
   }

You can update scope with :您可以使用以下命令更新范围:

public function scopeAge($query, $age)
{

    return $query->where('max_age','=',0)
        ->orWhere(function($q) use($age){
            return $q->where('min_age', '<=', $age)->where('max_age', '>=', $age);
        });

}

Then you can do :然后你可以这样做:

App\\Models\\CarPremium::age(18)->get()

You cannot use model properties ( $this->max_age ) in a scoped function.您不能在作用域函数中使用模型属性 ( $this->max_age )。 The query has not yet been executed so it's impossible to compare to a local value.查询尚未执行,因此无法与本地值进行比较。

A better way would be to add an or where to your query:更好的方法是or where查询中添加一个or where

public function scopeAge($query, $age)
{
    return $query
            ->where('max_age', 0)
            ->orWhere(function ($query) use ($age) {
                $query  
                    ->where('min_age', '<=', $age)
                    ->where('max_age', '>=', $age);
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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