没有的时候就给出了答案查询范围 https://laravel.com/docs/7.x/eloquent#query-scopes功能可用。
您可以覆盖主查询,仅适用于Post
模型,比如
class Post extends Eloquent
{
protected static $_allowUnapprovedPosts = false;
public function newQuery()
{
$query = parent::newQuery();
if (!static::$_allowUnapprovedPosts) {
$query->where('approved', '=', 1);
} else {
static::$_allowUnapprovedPosts = false;
}
return $query;
}
// call this if you need unapproved posts as well
public static function allowUnapprovedPosts()
{
static::$_allowUnapprovedPosts = true;
return new static;
}
}
现在,只需使用任何内容,但未经批准的用户不会出现在结果中。
$approvedPosts = Post::where('title', 'like', '%Hello%');
现在,如果您需要检索所有帖子,甚至是未经批准的帖子,那么您可以使用
$approvedPosts = Post::allowUnapprovedPosts()->where('title', 'like', '%Hello%');
更新(使用查询范围):
因为,Laravel 现在提供全局查询范围 https://laravel.com/docs/5.2/eloquent#global-scopes,利用它而不是这个黑客解决方案,请注意这个答案的日期,它太旧了,现在已经发生了很多事情。
// Using a local query scope
class Post extends Eloquent
{
public function scopeApproved($query)
{
return $query->where('approved', 1);
}
}
您可以像这样使用它:
$approvedPosts = Post::approved()->get();