如何在 Laravel Eloquent 查询构建器中实现“where not”?

3
这个 MySQL SQL 代码片段在 Laravel 中对应的 Eloquent 查询构建器是什么?
select * from `posts` left join `user_post_interactions` on `posts`.`id` = `user_post_interactions`.`post_id` where `posts`.`user_id` = 10 and not (`user_post_interactions`.`interaction_name` = 'hide' and `user_post_interactions`.`user_id` = 10)

我正在做的是:

$this->posts()->leftJoin('user_post_interactions', 'posts.id', '=', 'user_post_interactions.post_id')
            ->where(function($q) {
                $q->where('user_post_interactions.interaction_name', '<>', 'hide')
                    ->where('user_post_interactions.user_id', '<>', 10);
            });
但这并没有产生我预期的结果。

使用 whereRaw,更多详情请参考 https://laravel.com/docs/5.7/queries#raw-expressions - Gaurav Gupta
2个回答

5

您可以使用whereHas()方法,该方法将仅查询具有interaction且其中user_id不等于10的帖子:

$this->posts()->whereHas('interactions', function ($query) {
    $query->where('user_id', '!=', 10);
})->get();
请注意,这将需要一个带有interactions()关系的Post模型的Interaction模型。 如果您想在查询中包含interactions,请将->with('interactions')添加到查询链中。

1
您可以简单地运行:

$this->posts()->with(['interaction' => function($query){
            return $query->where("interaction_name","!=",'hide')
                ->where("user_id","!=",10);
        }]);

如果你想过滤具有交互的内容

$this->posts()->whereHas('interaction', function($query){
            return $query->where("interaction_name","!=",'hide')
                ->where("user_id","!=",10);
        });

我假设你的posts表与interaction有关联。


谢谢。但这是过滤互动。我想根据互动来过滤帖子。 - Gopal Gautam
@GopalGautam 在使用 with() 之前,您可以使用 whereHas() 来使用相同的块,请参见更新的答案。 - Chintan7027

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,