我需要创建一个函数,该函数应该只选择is_public=1和approved=1的帖子。但仅限客人使用。对于登录用户,它应该显示所有帖子。当类别试图找到子类别,并发布链接到该类别和所有子类别的帖子时,我的模型中存在自我关系的问题。
下面的功能正在做我需要的:但是
$categories = PostCategory::whereNull('parent_id')->with(
['posts' => function($q) {
$q->where('is_public', 1);
$q->where('approved', 1);
}])->with(['categories.posts' => function($q) {
$q->where('is_public', 1);
$q->where('approved', 1);
}])->with(['categories.categories.posts' => function($q) {
$q->where('is_public', 1);
$q->where('approved', 1);
}])->with(['categories.categories.categories.posts' => function($q) {
$q->where('is_public', 1);
$q->where('approved', 1);
}])->with(['categories.categories.categories.categories.posts' => function($q) {
$q->where('is_public', 1);
$q->where('approved', 1);
}])->orderBy('order')->get();
对于类别树的任何新级别,我需要添加一个新的WHERE子句:
categories.categories.categories.(UNLIMITED categories).posts
我知道这是愚蠢和不准确的。应该有另一种方法在每个类别和子类别中获得"公开"one_answers"批准"的帖子。
这是我的型号:
public function posts(){
return $this->belongsToMany(Post::class, 'post_category', 'category_id', 'post_id');
}
public function categories(){
return $this->hasMany(PostCategory::class, 'parent_id');
}
public function childrenCategories(){
return $this->hasMany(PostCategory::class, 'parent_id')->with('categories');
}
当然,我可以做下一步:
public function posts(){
return $this->belongsToMany(Post::class, 'post_category', 'category_id', 'post_id')->where('approved', 1)->where('is_public', 1);
}
但在这种情况下,它不会向登录用户显示所有帖子。请帮助我为该函数构建正确、准确的代码。提前感谢您!
您可以在post函数中检查用户是否经过身份验证
if(Auth::check()){
return $this->belongsToMany(Post::class, 'post_category', 'category_id', 'post_id');
}else{
return $this->belongsToMany(Post::class, 'post_category', 'category_id', 'post_id')->where('approved', 1)->where('is_public', 1);
}