【问题标题】:Use Eloquent model method when querying database查询数据库时使用 Eloquent 模型方法
【发布时间】:2025-11-23 00:55:02
【问题描述】:

使用名为 Foo 的 Eloquent 模型,包括名为 bar 的方法,我可以从另一个函数 baz 查询数据库时使用 bar 吗?否则我必须为bar 返回的每个对象调用baz

我想做这样的事情:

class Foo extends Model
{
    public function bar
    {
        return Bar::where('foo_id', $this->id)->sum('amount');
    }

    public function baz
    {
        return self::where('col', true)->with('bar')->take(5);
    }
}

【问题讨论】:

    标签: php database performance laravel eloquent


    【解决方案1】:

    当然可以,但最好是使用范围。这就是您定义范围的方式。

    public function scopeBaz($query)
    {
        return $query->where('col', true)->with('bar')->take(5);
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用Eloquent query scopes:

      class Foo extends Model
      {
          public function scopeBar($query)
          {
              return $query->where('foo_id', $this->id)->sum('amount');
          }
      
          public function baz
          {
              return Bar::where('col', true)->bar()->take(5);
          }
      }
      

      此外,您可以在控制器和其他类中使用bar(),而不仅仅是在模型中。

      【讨论】:

      • 这将返回一个 Bar 对象,而不是 Foo 对象
      最近更新 更多