在laravel中创造一个可链接的方法 [英] creating a chainable method in laravel

查看:104
本文介绍了在laravel中创造一个可链接的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在laravel的雄辩中创造自己的可链接的方法,但我错过了一些东西,不知道什么。这可能听起来有点坚果,但是看看我的下面的功能,以便更好地了解我想说的话。

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

//这工作很好
$ posts = Post :: custom_wh(array(1,2,3)) - > get() ;

//但是这表示custom_wh没有在查询类中定义
$ posts = Post :: where_in('tags',array(2,3,4),'AND') - > custom_wh(array(1,2,3)) - > get();

如果我理解正确,那么我的方法不符合另一种方法链接的条件?所以我想我的问题是如何在我的模型中创建一个可链接的方法?



PS我已经研究了laravel的查询生成器类,我看到可链接的方法返回该对象的实例,但是我找不到一种返回对象的方法,而不是我在上面的代码中完成的方式。任何形式的建议或建议受到高度评价。感谢提前。

解决方案

自从您的问题以来,Laravel提供了一种新的方法,称为查询范围。您可以在此处找到文档。



您只需编写一个前缀 scope 的函数,您就可以像其他查询构建器一样链接此方法:

  class Post Eloquent {

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

}

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


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?

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.

解决方案

Since your question, Laravel offer a new way of doing this, called "query scopes". You can find the doc here.

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(array(1, 2, 3))->get();
$posts = Post::orderBy('date')->whereCategories(array(1, 2, 3))->take(5)->get();

这篇关于在laravel中创造一个可链接的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆