【问题标题】:Where is Laravel model's static where function?! How does Laravel do that?Laravel 模型静态函数在哪里?! Laravel 是如何做到这一点的?
【发布时间】:2012-12-21 04:54:46
【问题描述】:

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

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

【问题讨论】:

  • 您正在寻找 Facade 但可能不适合模型,IMO。
  • Query Scopes 是 Laravel 的必经之路,就像下面所说的 mattiashallstrom

标签: laravel


【解决方案1】:

你试过这样的东西吗?

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

【讨论】:

  • 在您的类模型中(从 Eloquent 扩展而来)尝试添加静态方法 tall(),就像答案中的代码一样。
  • 你知道这行得通吗?如果是,如何?因为如果您在静态上下文中,代码将必须有所不同。
  • 您可以使用 static::where() 或 $this->where() ,它的工作原理相同,具体取决于上下文。
【解决方案2】:

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

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

然后在别处访问它

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

如果您确保在方法中不包含 ->get() 调用,而是在调用方法时包含它(如上),那么由于返回查询生成器,您应该能够添加其他 where 语句在打电话给get()之前给它@

$users = User::tall()->where("is_active", "=", 1)->get();

【讨论】:

    【解决方案3】:

    我认为查询范围是您正在寻找的: 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);
    }
    

    范围查询是可链接的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多