Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php laravel范围是否适用于每个模型实例?_Php_Laravel_Eloquent - Fatal编程技术网

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

Php laravel范围是否适用于每个模型实例?,php,laravel,eloquent,Php,Laravel,Eloquent,我使用的是Laravel 5.7 以及PHP7.2.10 我想要那些记录,如果max_age=0或者max_age>0,那么它应该检查给定的$age是否介于max_age和min_age之间 在CarPremium模型中 public function scopeAge($query, $age) { if ( $this->max_age == 0 ) { return $query; } else { return $query-&g

我使用的是Laravel 5.7 以及PHP7.2.10

我想要那些记录,如果max_age=0或者max_age>0,那么它应该检查给定的
$age
是否介于
max_age
min_age
之间

CarPremium
模型中

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

您可以使用以下命令更新范围:

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

}
公共函数scopeAge($query,$age)
{
返回$query->where('max_age','=',0)
->orWhere(功能($q)使用($age){
返回$q->where('min_age','=',$age);
});
}
然后你可以做:


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

不能在作用域函数中使用模型属性(
$this->max_age
)。查询尚未执行,因此无法与本地值进行比较

更好的方法是在查询中添加
或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);
            });
}
公共函数scopeAge($query,$age)
{
返回$query
->其中('max_age',0)
->orWhere(函数($query)使用($age){
$query
->其中('min_age','=',$age);
});
}

是否有必要调用
query()
?@ManzurulHoqueRumi是否有更好的解决方案?
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);
            });
}