首页 > 解决方案 > 将本地范围转换为全局范围或按父属性查询

问题描述

我想检索属于活动帖子的所有评论。

我的Posts模型上有一个本地范围,看起来像这样。

public function scopePublic($query) {
    return $query->whereHas('post', function ($q) {
        $q->where('is_public', true);
    });
}

哪个工作正常,但是PHP message: PHP Fatal error: Allowed memory size of X bytes exhausted一旦我想将它转换为这样的全局范围就会中断:

static::addGlobalScope('is_public', function (Builder $builder) {
    return $builder->whereHas('post', function ($q) {
        $q->where('is_public', true);
    });
});

我的最终目标是让所有评论查询仅显示公众评论,除非我明确要求不要这样做。

我已经通过了很多解决方案。我已经尝试在评论中加入帖子,并且尝试添加子选择以不走运。

$builder->addSelect(['is_public' => Post::select('is_private')
   ->whereColumn('id', 'comment.post_id')->limit(1)
]);

$builder->join('posts','posts.id','=','comments.post_id')
    ->where('comments.is_private', false);

标签: sqllaraveleloquent

解决方案


创建一个新类 PublicScope

use Illuminate\Database\Eloquent\Scope;

class CommentPublicScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->whereHas('post', function ($q) {
            $q->where('is_public', true);
        });
    }
}

然后你可以添加全局范围

Class Comment extends Model
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new CommentPublicScope);
    }
}

推荐阅读