Laravel中的高级whereNotNull语句

Laravel中的高级whereNotNull语句,laravel,laravel-4,query-builder,Laravel,Laravel 4,Query Builder,是否可以在Laravel 4中执行以下操作 DB::table('myTable') ->select(DB::raw($columnNames)) ->whereNotNull(function($query) use($columns) { foreach ($columns as $column) { $query->whereNotNull($column); } }) ->g

是否可以在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,并且该行不应成为结果的一部分。因此,只应返回至少有一个非空值的行。

尝试使用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()

如果这些是唯一的where,您甚至不需要嵌套where。重要提示:
或whereNotNull
而不是
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条件(尤其是带有
的条件),则需要嵌套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'

因此,条件是:至少有一个
$列
不能为
NULL
?我已在问题中澄清了条件,谢谢!