【问题标题】:How to do IS NOT NULL in a Laravel query如何在 Laravel 查询中执行 IS NOT NULL
【发布时间】:2017-05-09 02:44:05
【问题描述】:

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

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

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

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

likes 表“属于”sources 表和 posts 表。

编辑:

我使用的是 Laravel 版本 5.2.45

【问题讨论】:

  • 请指定您使用的 laravel 版本。

标签: php mysql laravel blade


【解决方案1】:

您可以使用whereNotNull() 方法。

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

更新

看来$posts 是一个集合。在这种情况下,您必须使用filter()。例如:

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

【讨论】:

  • 当我尝试那个时收到错误消息ErrorException in Macroable.php line 74: Method whereNotNull does not exist.
  • 我这样称呼它:`

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

    `
  • Offtopic :您应该考虑检查控制器中的数据,而不是检查视图。
  • 这似乎可行,谢谢!不过还是得做更多的测试。
【解决方案2】:

你试过这样吗……

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

也可以试试

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

【讨论】:

  • 没有where_not_null,是whereNotNull()
  • source_id &lt;&gt; NULL 永远不会是 TRUE。
【解决方案3】:

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

如果版本是 Laravel 4./5.,那么您的查询将是这样的,

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

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

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

【讨论】:

  • 我在尝试那个时收到错误消息ErrorException in Macroable.php line 74: Method whereNotNull does not exist.
  • 我尝试了上面的查询,它正在工作。所以请告诉我你试过什么?
  • `

    总点赞数:{{$post->likes->where('post_id', $post->id)->whereNotNull('source_id')->sum('like ')}}

    `对不起,封闭的代码似乎不起作用。
  • 尝试从上述查询中删除 sum(like)。
  • 我仍然收到错误Method whereNotNull does not exist.
猜你喜欢
  • 1970-01-01
  • 2015-04-25
  • 2018-11-25
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2012-01-29
  • 2014-12-08
  • 2013-10-09
相关资源
最近更新 更多