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

时间:2019-02-13 14:47:46

标签: php laravel eloquent

我正在使用Laravel 5.7 和PHP 7.2.10。

我想要那些max_age = 0或max_age> 0的记录,那么它应该检查给定的df$variable3 <- paste0(df$variable, "3") df$value3 <- c(runif(40, min=0, max=3), rnorm(100)) 是否在ggplot(df,aes(variable, value)) + geom_beeswarm(aes(variable2),priority='random',cex=2.5) + geom_boxplot() + geom_boxplot(aes(variable3, value3), color="white") + # this is the boxplot that we will hide (notice the color choice) scale_x_discrete(breaks = c(letters[1:7])) + theme(axis.text.x = element_text(hjust=-6), # adjust to center the x-labels axis.ticks.x = element_blank(), panel.background = element_rect(color="white", fill="white"), panel.grid.major.x = element_blank(), panel.grid.major = element_blank(), # to remove grid lines panel.grid.minor = element_blank(), axis.line = element_line(size = 0.5, linetype = "solid", colour = "black")) $age之间。

max_age模型中

min_age

我正在获取年龄不在CarPremiumpublic 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); } } 之间的记录,而没有获取max_age年龄的记录。

修补匠

min_age

2 个答案:

答案 0 :(得分:1)

您可以使用:

更新范围
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);
        });

}

那么您可以做:

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

答案 1 :(得分:1)

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

一种更好的方法是在您的查询中添加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);
            });
}