如何在 Laravel 查询中执行 IS NOT NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41300674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:59:35  来源:igfitidea点击:

How to do IS NOT NULL in a Laravel query

phpmysqllaravelblade

提问by Adam Dedanga

I'm trying to do this SQL statement and outputting it using the blade engine:

我正在尝试执行此 SQL 语句并使用刀片引擎输出它:

" SELECT SUM(like) FROM likes WHERE post_id = ". $post->id. " AND source_id IS NOT '' "

I don't know how to do it, I tried this yesterday but it didn't work:

我不知道该怎么做,我昨天试过了,但没有用:

{{$post->likes->where('post_id', $post->id)->where('source_id', '<>', '')->sum('like')}}

The likestable "belongsTo" both the sourcestable and the poststable.

喜欢表“属于关联”两个表和职位表。

Edit:

编辑:

I'm using Laravel version 5.2.45

我正在使用 Laravel 版本5.2.45

回答by Alexey Mezenin

You can use whereNotNull()method.

您可以使用whereNotNull()方法。

https://laravel.com/docs/5.3/queries#where-clauses

https://laravel.com/docs/5.3/queries#where-clauses

Update

更新

It seems $postsis a collection. In this case, you'll have to use filter(). For example:

好像$posts是个收藏。在这种情况下,您必须使用filter(). 例如:

$collection->filter(function ($item) {
    return $item['some_value'] !== null;
});

回答by Hikmat Sijapati

Did you try like this...

你这样试过吗...

{{$post->likes->where('post_id', $post->id)->whereNotNull('source_id')->sum('like')}}

Also try as

也尝试作为

{{$post->likes->
where([
    ['post_id', '=', $post_id],
    ['source_id', '<>', NULL],])
->sum('like') }}

回答by Bhavin

For Laravel 4./5. its whereNotNull() and for Laravel 3: its where_not_null().

对于 Laravel 4./5。它的 whereNotNull() 和 Laravel 3:它的 where_not_null()。

So your query will be this if version is Laravel 4./5.,

所以如果版本是 Laravel 4./5.,你的查询将是这个

{{$post->likes->where('post_id', $post->id)->whereNotNull('source_id')->sum('like')}}

Query will be this if version is Laravel 3,

如果版本是 Laravel 3,查询将是这个,

{{$post->likes->where('post_id', $post->id)->where_not_null('source_id')->sum('like')}}