【问题标题】:Advanced whereNotNull statement in LaravelLaravel 中的高级 whereNotNull 语句
【发布时间】:2014-12-24 07:05:21
【问题描述】:

是否可以在 Laravel 4 中执行以下操作? ...

DB::table('myTable')
    ->select(DB::raw($columnNames))
    ->whereNotNull(function($query) use($columns) {
        foreach ($columns as $column) {
            $query->whereNotNull($column);
        }
    })
    ->get();

如果我有下表:

table: myTable
id  |   name    |   age     |   weight  
======================================
1    Jane        NULL        150
2    NULL        12          80
3    Bob         NULL        NULL
4    John        22          120
5    Cody        NULL        NULL

如果$columns[age, weight] 并且$columnNames'age, weight',那么应用上面的 whereNotNull 语句,我希望输出如下:

age     |    weight
===================
NULL         150
12           80
22           120

我怎样才能完成这项工作?

更新:

条件是返回所选列不为空的所有行。因此,whereNotNull 子句必须应用于每行中的每个(选定)列。如果所有列都是 NULL,那么 whereNotNull 将返回 false 并且该行不应该是结果的一部分。因此,应该只返回至少有一个非 NULL 值的行。

【问题讨论】:

  • 所以条件是:$columns至少有一个不能是NULL
  • 我已经澄清了我的问题,谢谢!

标签: laravel laravel-4 query-builder


【解决方案1】:

如果这些是唯一的地方,你甚至不需要嵌套的地方。重要提示:orWhereNotNull 而不是 whereNotNull,因此只有一列必须不是 NULL

$query = DB::table('myTable')->select(DB::raw($columnNames));

foreach($columns as $column){
    $query->orWhereNotNull($column);
}

$result = $query->get();

另外(至少在您的示例中)您不需要单独的变量$columnNames,因为select 将接受列名数组。

$query = DB::table('myTable')->select($columns);

如果您碰巧需要更多 where 条件(尤其是带有 AND 的条件),您需要一个嵌套的 where:

$query = DB::table('myTable')->select(DB::raw($columnNames));

$query->where(function($q) use ($columns){
    foreach($columns as $column){
        $q->orWhereNotNull($column);
    }
});

$result = $query->get();

嵌套的 where 将在 where 子句周围放置 ( )。这意味着而不是:

WHERE age IS NOT NULL OR weight IS NOT NULL AND foo = 'bar'

你得到:

WHERE (age IS NOT NULL OR weight IS NOT NULL) AND foo = 'bar'

【讨论】:

    【解决方案2】:

    尝试使用 where() 作为包装方法。这只会显示同时具有年龄和体重的记录。

    DB::table('myTable')
    ->select(DB::raw($columnNames))
    ->where(function($query) use($columns) {
        foreach ($columns as $column) {
            $query->whereNotNull($column);
        }
    })
    ->get();
    

    要显示任何具有年龄或体重的记录,请在循环中使用 orWhereNotNull()。

    我看不出循环不起作用的原因,因为您实际上是在这样做:

    $query = $query->whereNotNull('age'); $query = $query->whereNotNull('weight'); $results = $query->get();

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      相关资源
      最近更新 更多