如何在 laravel eloquent 查询生成器中实现“where not”

Gop*_*tam 3 sql laravel eloquent laravel-5

这个 mysql sql 片段的 laravel 等效雄辩查询生成器是什么:

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)
Run Code Online (Sandbox Code Playgroud)

我正在做的是:

$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);
            });
Run Code Online (Sandbox Code Playgroud)

但这并没有产生我预期的结果

thi*_*vin 5

您可以使用whereHas(),它只会查询具有interactionwhereuser_id不等于 的帖子10

$this->posts()->whereHas('interactions', function ($query) {
    $query->where('user_id', '!=', 10);
})->get();
Run Code Online (Sandbox Code Playgroud)

请注意,这将需要一个具有模型关系的Interaction模型。interactions()Post

如果您想包含interactions在查询中,请添加->with('interactions')到查询链中。