繁体   English   中英

Laravel查询哪里有和哪里

[英]Laravel Query whereHas and whereIn

在我的代码中,我应用了多个搜索过滤器。 以下是我没有得到预期结果的核心部分。

结果应该是用户具有与之关联的特定帖子,或者没有与之关联的帖子(通过whereHas期望)并且具有特定状态(例如available_now下面的示例)。

但是下面的查询结果还提供了特定的结果类型,其中用户连接了特定的帖子(预期),但结果包括状态不是available_now (意外的)的用户。

我希望查询同时应用这两个条件。 我想念什么吗?

$users = User::query();

$users = $this->filter1($users);
$users = $this->filter2($users);

private static function filter1($users) {
    $post_id = 5;

    $users->whereHas('posts', function ($query) use ($post_id) {
        $query->where('id', $post_id);
    })->orDoesntHave('posts');

   return $users;
}

private static function filter2($users) {
    $availability = array('available_now');
    $users->whereIn('availability', $availability); // I'm using whereIn because in some cases the $availability array has multiple values

    return $users;
}

return $users->get();

我认为问题来自orDoesntHave 在查询中使用括号以确保您的条件按预期工作:

$users = User::query();

$users = $this->filter1($users);
$users = $this->filter2($users);

private static function filter1($users) {
    $post_id = 5;

    $users->where(function ($query) use ($post_id) { //Will add parenthesis around this part of the query
        $query->whereHas('posts', function ($subquery) use ($post_id) {
            $subquery->where('id', $post_id);
        })->orDoesntHave('posts');
    });

   return $users;
}

private static function filter2($users) {
    $availability = array('available_now');
    $users->whereIn('availability', $availability);

    return $users;
}

return $users->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM