在 Laravel 中创建一个可链接的方法

2021-12-26 00:00:00 php laravel eloquent

我一直在尝试在 laravel' eloquent 中创建我自己的可链接方法,但我遗漏了一些东西并且不确定是什么.这听起来可能有点疯狂,但请查看下面我的函数,以更好地了解我想说的内容.

I have been trying to create my own chainable method in laravel' eloquent but I'm missing something and not sure what. This may sound a little bit nuts but have a look at my function below to get a better idea of what I'm trying to say.

class Post extends Eloquent{
    public static function custom_wh($data){
        return static::where_in('categories_id', $data, 'AND');
    }
}

//this works fine
$posts = Post::custom_wh(array(1, 2, 3))->get();

//but this says custom_wh is not defined in the query class
$posts = Post::where_in('tags', array(2, 3, 4), 'AND')->custom_wh(array(1, 2, 3))->get();

如果我理解正确,那么我的方法没有资格在另一个方法之后链接?所以我想我的问题是如何在我的模型中创建一个可链接的方法?

if I understand correctly then my method is not eligible to chain after another method? So I guess my question is how can I create a chainable method in my model?

PS 我已经查看了 laravel 的查询构建器类,在那里我看到可链接的方法返回该对象的实例,但除了我在代码中完成的方式之外,我找不到返回该对象的方法多于.任何形式的建议或建议都非常感谢.提前致谢.

P.S I have looked into the laravel's query builder class where I have seen that the chainable methods returns the instance of that object but I couldn't find a way to return the object other than the way I've done in the code above. Any kind of suggestion or advice is highly appreciated. Thanks in advance.

推荐答案

您可以在 Laravel 中使用查询范围"来做到这一点.您可以在此处找到文档.

You can do that in Laravel with the "query scopes". You can find the doc here.

你只需要写一个带有前缀scope的函数,你就可以像其他查询构建器一样链接这个方法:

You just have to write a function with the prefix scope and you will be able to chain this method like the other query builder ones :

class Post extends Eloquent {

    public function scopeWhereCategories($query, $categories)
    {
        return $query->whereIn('categories_id', $categories, 'AND');
    }

}

$posts = Post::whereCategories([1, 2, 3])->get();
$posts = Post::orderBy('date')->whereCategories([1, 2, 3])->take(5)->get();

相关文章