Laravel where with if else

Laravel where with if else

在我的 Laravel 项目中,我正在构建一个带有一些条件的查询。 有一个问题我无法解决

我有一个查询如下

$query = SocialMediaFeed::where('location_id', $location_id);

现在有一些 Feed 项 'self' = true.. 这些应该首先从结果中忽略,除非有 $filters 数组。

if(!$filters) {
    $query = $query->where('self', '<>', true);
}

现在我想知道,如果有过滤器,它应该包括我在 self 不等于 true 时得到的数据,还有如果是 true 的数据..

我尝试了以下方法,但只有 returns self=true 的帖子,而不是所有与 self=true

结合的帖子
$query = $query
    ->where('self', '<>', true)
    ->where('self', true)
    ->orWhereNull('self');

因此,如果您有过滤器,则无需执行任何操作:

$query = SocialMediaFeed::where('location_id', $location_id);

if (!$filters) {
  $data= $query->where('self',true)->get();
} else {
  $data= $query->get();
}

您可以为此使用 Conditional Clauses

// false: All social media feeds except where self is not true
// true: All social media feeds
$filters = false;
$query = SocialMediaFeed::where('location_id', $location_id)
->when(!$filters, function ($query) {
    return $query->where('self', '!=', true);
})->get();

过滤器只能减少结果集,不能增加。想一想过滤器在现实生活中的作用,它删除东西,从不添加它们。

如果我理解你的要求,我会这样做:

$query = SocialMediaFeed::where('location_id', $location_id);
if(!$filters) {
    $query = $query->where('self', '<>', true);
} else {
    $query = $query->orWhere('self', true);
}

这将 return location_id = $location_id AND self <> 未设置 $filters 时的所有行以及 location_id 的所有行= $location_id 或 self = true.

如果你真的只需要进行一个查询然后过滤它,反转你正在做的事情,查询 location_id = $location_id OR self = true 并过滤掉 self = true for当未设置 $filters 时。

但是,您发布的这段代码没有任何意义:

$query = $query
   ->where('self', '<>', true)
   ->where('self', true)
   ->orWhereNull('self');

我认为您应该查看 documentation。对 where 的多次调用与 'AND' 连接,因此 self = true AND self <> true 将以 0 个结果结束。

所以我不能 100% 确定您要做什么。希望我回答了你的问题。