Select 其中所有 3 列不同时为空(Laravel 查询生成器)

Select where all 3 columns are not null at the same time (Laravel Query Builder)

articles 数据库 table(和 Article 模型)具有(除其他外)这 3 列:

如何select所有这 3 列的文章不是NULL同时?

因此,如果 col_1 = NULLcol_2 = NULL 以及 col_3 = NULL - 不要 select(包括)那些文章。但是,如果这些列中的一个或多个不是 NULL - 那么 select(包括)它。

此查询构建器如下所示:

Article::select('articles.*')-> ... ->get();

当然,不是 ... 而是检查所有这 3 列是否同时 not null

我知道这是错误的:

Article::select('articles.*')
       ->whereNotNull('col_1')
       ->whereNotNull('col_2')
       ->whereNotNull('col_3')
       ->get();

... 因为它不会 select(包括)其中一个为 NULL(col_1)和其余(col_2col_3) 不为 NULL。

----------------更新:----------------

澄清一下:我想 select(包括)none 或 col_1、[=17 中的一两个 的文章=],并且 col_3NULL,但是 如果三个都不是 NULL

您要查找的查询是:

SELECT
    *
FROM
    `articles`
WHERE
    `col_1` IS NOT NULL
    OR `col_2` IS NOT NULL
    OR `col_3` IS NOT NULL
;

在 Laravel 中,这将导致以下结果:

Article::orWhereNotNull('col_1') 
   ->orWhereNotNull('col_2')
   ->orWhereNotNull('col_3')
   ->get();

如果我没记错的话,select('articles.*') 中完全相同的 select 是由 Eloquent 完成的。也许第一个 orWhereNotNull 应该是 whereNotNull 但是你还得自己去寻找。

您正在寻找的查询生成器是:

$articles = Article::where(function($q){
   return $q->whereNotNull('col_1')
       ->orWhereNotNull('col_2')
       ->orWhereNotNull('col_3');
})->get();

在闭包中将 or 子句一起添加的原因是 to group them。因此,如果将来您想添加另一个地方,例如:

SELECT
    *
FROM
    `articles`
WHERE 
    (`col_1` IS NOT NULL OR `col_2` IS NOT NULL OR `col_3` IS NOT NULL)
    AND
    `type` = 1
;

您直接添加:

$articles = Article::where(function($q){
   return $q->whereNotNull('col_1')
       ->orWhereNotNull('col_2')
       ->orWhereNotNull('col_3');
})
->where('type', 1)->get();

如果你这样做:

$articles = Article::orWhereNotNull('col_1') 
   ->orWhereNotNull('col_2')
   ->orWhereNotNull('col_3')
   ->where('type', 1)
   ->get();

它进行以下查询,不是您需要的查询:

SELECT
    *
FROM
    `articles`
WHERE 
    `col_1` IS NOT NULL 
    OR `col_2` IS NOT NULL 
    OR `col_3` IS NOT NULL
    AND `type` = 1
;

一个更简单的方法是

Article::select('articles.*')
   ->whereNotNull(['col_1','col_2','col_3'])
   ->get();