【问题标题】:Laravel multilevel relationship with dynamic WHERE clauseLaravel 与动态 WHERE 子句的多级关系
【发布时间】: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


    【解决方案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);
        }
    

    【讨论】:

    • 在这种情况下它会起作用,但想象一下我会有不同类型的选项。例如'public'、'approved'、'deleted'、post 'created after April 5th',以及许多其他过滤器,用户可以选择其中的任何一个或两个选项。在这种情况下,我不想在模型中创建不同的 IF ELSE。我只需要构建 WHERE 子句并将其发送到模型。我确信这是可能的。我只是找不到正确的方法。 (((
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2016-12-28
    • 2016-12-31
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多