如果关系为null,Laravel不显示数据

问题描述 投票:0回答:1

我有此代码:

 $rightsRequests = $this->company->rightsRequests()
            ->orderBy('created_at','DESC')
            ->with(['post' => function($q){
                $q->where('posts.status','!=',100);
            },'userWhoRequested'])
            ->get();

我正在过滤数据,如果关系“发布”的状态为100,它将使posts对象成为null。像这样:"posts" : null

该查询显示这些数据:

[
   {
      "post_id":57,
      "network_id":2,
      "source_id":3,
      "feed_id":2,

      "user_who_requested":{
         "id":6,
         "notification":2,

      },
      "post":null
   },
   {
      "post_id":57,
      "network_id":2,
      "source_id":3,
      "feed_id":2,
      "user_who_requested":{
         "id":6,
         "notification":2,
      },

      "post":{
         "id":58,
         "network_id":2,
         "status":1,

      }
   }
]

如果关系posts100,或者我应该说null,我怎么不显示数据?因此,在示例输出中,由于posts为空,因此它不应显示该第一个键。因为posts不为null,所以它应该只显示此数据:

[
   {
      "post_id":57,
      "network_id":2,
      "source_id":3,
      "feed_id":2,
      "user_who_requested":{
         "id":6,
         "notification":2,
      },

      "post":{
         "id":58,
         "network_id":2,
         "status":1,

      }
   }
]

如何在雄辩的查询中做到这一点?

我很难解释,对不起!

非常感谢您的帮助,谢谢!

laravel eloquent
1个回答
0
投票

您可以使用雄辩的whereHas方法。您的代码如下所示:

$rightsRequests = $this->company->rightsRequests()
        ->orderBy('created_at','DESC')
        ->whereHas('post')
        ->with(['post' => function($q){
            $q->where('posts.status','!=',100);
        },'userWhoRequested'])
        ->get();

如果帖子为空,则不会显示。

© www.soinside.com 2019 - 2024. All rights reserved.