【问题标题】:How to implement "where not" in laravel eloquent query builder如何在 laravel eloquent 查询构建器中实现“where not”
【发布时间】:2019-09-06 06:50:30
【问题描述】:

这个 mysql sql sn-p 的 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);
            });

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

【问题讨论】:

标签: sql laravel laravel-5 eloquent


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

【讨论】:

  • 谢谢。但这是过滤交互。我想根据互动过滤帖子
  • @GopalGautam 您可以在之前使用whereHas() 使用相同的块,请参阅更新的答案
【解决方案2】:

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

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

请注意,这需要Interaction 模型与Post 模型上的interactions() 关系。

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

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2017-11-28
    • 2020-03-19
    • 2019-02-13
    • 2015-07-05
    • 2017-08-30
    • 2016-03-30
    • 2016-02-09
    • 2021-11-16
    相关资源
    最近更新 更多