Eloquent可以生成类似于”WHERE (column_1 OR column_2 IS NOT NULL)”的WHERE子句吗?

huangapple go评论59阅读模式
英文:

Can Eloquent generate a WHERE clause like "WHERE (column_1 OR column_2 IS NOT NULL)"?

问题

可以使用Eloquent生成一个精确像标题中示例的WHERE子句的查询吗?

我最接近的尝试是使用Where()和orWhere(),但它输出

(column_1 IS NOT NULL OR column_2 IS NOT NULL)

这与标题中的查询产生不同的结果!

有人可以解释一下为什么这两个WHERE子句产生不同的结果吗?

英文:

Is it possible to make eloquent generate a query with a WHERE clause precisely like the example in the title?

The closest I got was with Where() and orWhere(), but that outputs

(column_1 IS NOT NULL OR column_2 IS NOT NULL),

which gives different results than the query in the title!

Can someone also explain why these two WHERE clauses give different results?

答案1

得分: 0

在Eloquent上使用where closure

$results = YOUR_MODEL::where(function($query) {
    $query->whereNotNull('column_1')
        ->orWhereNotNull('column_2');
})->get();

这将生成一个带有WHERE子句的查询,类似于(column_1 IS NOT NULL OR column_2 IS NOT NULL)

英文:

Use a where closure on Eloquent.

$results = 
YOUR_MODEL::where(function($query) {
     $query->whereNotNull('column_1')
         ->orWhereNotNull('column_2');
    })->get();

This will generate a query with a WHERE clause that looks like (column_1 IS NOT NULL OR column_2 IS NOT NULL).

答案2

得分: 0

在评论中,@Andrew指出,我错误地假设查询

WHERE (column_1 OR column_2 IS NOT NULL)

检查两个列是否为null值,并返回所有结果,其中column_1、column_2或两者都不为null。

实际上,这个查询检查column_1是否为true/false,column_2是否为null,并返回column_1为true或column_2不为null或两者都不为null的结果。

生成类似这样查询的Eloquent代码是:

$query = DB::table('your_table')
    ->where('column_1', true)
    ->orWhereNotNull('column_2');

编辑:正如@Ali Raza指出的,您还必须使用where closure来确保查询生成器输出与问题中完全相同的查询(带有括号):

$query = DB::table('your_table')
    ->where(function (Builder $q) {
        $q->where('column_1', true)
          ->orWhereNotNull('datumPrenosa');
    });
英文:

As @Andrew pointed out in the comment to op, I incorrectly assumed that query

WHERE (column_1 OR column_2 IS NOT NULL)

checks both columns for null value, and returns all results where eirther column_1, column_2 or both are not null.

The query in fact checks column_1 for true/false, and column_2 for null, and returns results where column_1 is true or column_2 is not null or both.

Eloquent code that outputs a query like that is:

$query = DB::table('your_table')
    ->where('column_1', true)
    ->orWhereNotNull('column_2')

Edit: As @Ali Raza pointed out, you must also use a where closure to make the query builder output the query exactly as it is in the question (with parantheses);

$query = DB::table('your_table')
    ->where(function (Builder $q) {
        $q->where('column_1 ', true)
          ->orWhereNotNull('datumPrenosa');
        })

huangapple
  • 本文由 发表于 2023年4月19日 22:02:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定