【问题标题】:Laravel extending EloquentLaravel 扩展 Eloquent
【发布时间】:2014-02-15 04:48:00
【问题描述】:

我对 Laravel、命名空间和类相当陌生。我有一个特定于应用程序的类,该类已正确自动加载并具有自己的命名空间。这个类扩展了 Eloquent。

我想做的是找到优化我的代码的方法。这是一个示例:

$collection = Collection::where('user_id', '=', Auth::user()->id)->with('photos')->get();

所以我有一个 Collection 模型,它扩展了我自己的 Appspecific 抽象类。上面的代码没有错,但是我会做很多,我很想优化它以提高可读性。像这样的:

$collection = Collection::getMine()->with('photos')->get();

现在在我的应用特定类中,我有这个:

public static function getMine() {
    if(\Auth::guest())
        return false;

    return $this->where('user_id', '=', \Auth::user()->id); //would not work coz im not in object context

}

我做错了什么?我在正确的课堂上这样做吗?我是否应该在另一个扩展了其他内容的类上执行此操作,比如 BuilderClass?

【问题讨论】:

    标签: php oop laravel eloquent


    【解决方案1】:

    你正在寻找Eloquent's scope methods:

    public function scopeGetMine ($query)
    {
        if(\Auth::guest()) return false;
    
        return $query->where('user_id', \Auth::user()->id);
    
    }
    

    那就随心所欲地使用吧:

    $collection = Collection::getMine()->with('photos')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 2015-02-23
      • 2015-03-25
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多