【问题标题】:Laravel search following the DRY principleLaravel 搜索遵循 DRY 原则
【发布时间】:2020-04-08 06:59:11
【问题描述】:

我有多个搜索功能,看起来都像这样:

    public function searchEntity(Request $request)
    {       
        ... // Some variables and other stuff 

        $q = $request->q;
        $entities = Entity::where('name', 'LIKE', '%' . $q . '%')->paginate(15);
        $entities->appends(['search' => $q]);
        return view(
            'entity',
            compact('entities', ...)
        );
    }

有没有更好的方法来做到这一点,我每次尝试搜索 Eloquent 实体时都不重复相同的代码,还是将这些方法分开更好?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我的建议是创建具有范围的 Trait。

    所以你的特质中会有这样的东西:

    trait search
    {
        public function scopeSearch(Builder $builder)
        {
            $request = request();
            $q = $request->q;
    
            return $builder->where('name', 'LIKE', '%' . $q . '%')->paginate(15);
        }
    
    }
    

    比在你的模型中使用你的特质。在每个模型的控制器中,您可以这样做:

    $entities = Entity::search();
    

    只需阅读 Traits 和 Scopes,我认为这就是您所需要的。

    一些建议:link-1link-2

    祝你好运!

    【讨论】:

    • 那不是范围
    • 这不是最佳的做法,应该包括一个范围。
    • 我说要在 trait 中创建作用域。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多