我一直在尝试在 laravel' eloquent 中创建自己的可链接方法,但我错过了一些东西,并且不确定什么。这听起来可能有点疯狂,但请看一下我下面的函数,以便更好地了解我想说的内容。
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();
如果我理解正确,那么我的方法不符合在另一个方法之后链接的条件?所以我想我的问题是如何在我的模型中创建可链接的方法?
P.S 我研究了 laravel 的查询构建器类,在其中我看到可链接方法返回该对象的实例,但除了我在上面的代码中所做的方式之外,我找不到返回该对象的方法。任何形式的建议或建议都将受到高度赞赏。提前致谢。
您可以在 Laravel 中使用“查询范围”来做到这一点。你可以找到文档here.
你只需要编写一个带有前缀的函数scope
您将能够像其他查询生成器一样链接此方法:
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)