Php laravel范围是否适用于每个模型实例?
我使用的是Laravel 5.7 以及PHP7.2.10 我想要那些记录,如果max_age=0或者max_age>0,那么它应该检查给定的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
$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);
});
}