【发布时间】:2021-07-30 01:01:59
【问题描述】:
我需要创建一个函数,该函数应仅选择 is_public = 1 且已批准 = 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
而且我知道这是愚蠢和不准确的。应该有另一种方法来获取每个类别和每个子类别中的“公开”和“批准”帖子。
那是我的模型:
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);
}
但在这种情况下,它不会向登录用户显示所有帖子。 请帮助我为该功能构建正确且准确的代码。 提前非常感谢您!
【问题讨论】:
标签: php laravel eloquent eloquent-relationship