Laravel模型的静态功能在哪里?! Laravel是如何做到的?

时间:2013-01-07 12:50:45

标签: laravel

我有一个Eloquent模型,我想为特定模型创建一些快捷函数,例如User::tall()而不是写User::where("height", ">", 185)。但是我希望它们是静态的以及非静态的方法,所以我也可以调用$user->where('is_active', '=', '1')->tall()

我有办法吗? 我可以看到Laravel以某种方式设法做到这一点,因为可以从两个上下文中调用。我查看了代码,但我只能找到一个对象方法。

3 个答案:

答案 0 :(得分:4)

我认为查询范围正是您所寻找的: http://laravel.com/docs/eloquent#query-scopes

public function scopeTall($query)
{
    return $query->where('height', '>', 185);
}

您还可以为查询范围指定参数,例如:

public function scopeTall($query, $height = 185)
{
    return $query->where('height', '>', $height);
}

范围查询是可链接的。

答案 1 :(得分:1)

你尝试过这样的事吗?

class YourClassModel extends Eloquent
{
     public static function tall() 
     {
         // Return the result of your query
         return ...;
     }
}

答案 2 :(得分:0)

只需在用户类上编写一个新的静态方法

class User extends Eloquent {
    public static function tall() {
        return User::where("height", ">", 185);
    }
}

然后在其他地方访问

$users = User::tall()->get();

如果您确保在方法中不包含->get()调用,而是在调用方法时包含它(如上所述),那么由于返回了查询构建器,您应该能够添加其他调用get()

之前的语句
$users = User::tall()->where("is_active", "=", 1)->get();