【问题标题】:How to share scopes between classes in Laravel 5如何在 Laravel 5 中的类之间共享范围
【发布时间】:2016-08-03 16:52:55
【问题描述】:

我有几个具有相同功能的 Laravel 模型。

我正在尝试实现某种 ::All() 功能,但背后有另一个逻辑。

例如:我所有的模型都有一个“活动”布尔标志,这意味着我得到了我所有的语言,例如:$language = Language::where('active', 1)->orderBy('name')->get();。兴趣爱好、学期等也是如此。

我正在尝试在我的 base_model 中执行类似的操作,所有其他模型都从该模型扩展:

public static function getActive()
{
    return this::where('active', 1)->orderBy('name')->get();
}

这将为我节省大量冗余代码,但作为一个新手,我正在为代码苦苦挣扎。

如何动态定义要检索的模型?

有什么想法吗?

【问题讨论】:

    标签: php laravel oop laravel-5


    【解决方案1】:

    您可以为此使用 Laravel query scopes。例如:

    //your base model
    class BaseModel extends Model
    {
        //every class inheriting from this will have this scope
        public function scopeActive($query)
        {
            return $query->where('active', 1)->orderBy('name')->get();
        }
    }
    
    //your child models will inherit the scope from the parent class
    class Language extends BaseModel
    { 
        //your model's methods
    }
    
    //use the scope to get all the active languages
    $languages = Language::active();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2010-11-02
    • 1970-01-01
    相关资源
    最近更新 更多