sql - 将本地范围转换为全局范围或按父属性查询
问题描述
我想检索属于活动帖子的所有评论。
我的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);
解决方案
创建一个新类 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);
}
}
推荐阅读
- javascript - (JS)未捕获的类型错误:无法读取未定义的属性“删除”
- java - 如何将每一行保存在共享首选项而不是最后一行?
- python - Python asyncio队列没有显示任何异常
- visual-studio-code - VS Code:创建自定义片段/快捷方式
- c++ - TBB:如何获得当前任务竞技场?
- javascript - 如何通过单击按钮触发功能,该功能已设置为在 AngularJS 中使用“Enter”按键触发?
- mysql - 根据一列中的值按组计算百分比
- swift - 映射 Swift 结合未来到另一个未来
- c++ - 函数返回时的 Cpp 调试断言错误
- javascript - 如何在adobe livecycle中拆分字符串并用该字符串内的值填充动态表?