如何在Laravel雄辩的查询生成器中实现“哪里不行”

时间:2019-04-16 08:19:34

标签: sql laravel laravel-5 eloquent

此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)

我正在做的是:

$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);
            });

但这不会产生我预期的结果

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以使用whereHas()来查询只有interaction不等于user_id的{​​{1}}的帖子:

10

请注意,这将需要在$this->posts()->whereHas('interactions', function ($query) { $query->where('user_id', '!=', 10); })->get(); 模型上具有Interaction关系的interactions()模型。

如果您想在查询中包含Post,请在查询链中添加interactions