【问题标题】:Check if collection contains a value检查集合是否包含值
【发布时间】:2017-06-04 09:58:54
【问题描述】:

我已经建立了关系(我认为是正确的)。我有 3 个表,用户、cmets 和 cmets 的喜欢表。

在我的刀片中,我可以使用这个访问{{ $comment->commentLikes }},它会返回给我:

[{"id":85,"comment_id":12,"user_id":1,"action":1},
{"id":86,"comment_id":12,"user_id":3,"action":1},
{"id":87,"comment_id":12,"user_id":4,"action":1},
{"id":88,"comment_id":12,"user_id":6,"action":1},
{"id":89,"comment_id":12,"user_id":9,"action":1}]

user_id代表like的所有者。

现在我想检查这个集合是否有经过身份验证的用户,换句话说,当前用户是否喜欢这个评论。有没有办法做到这一点而不是使用 for 循环?也许像{{ $comment->commentLikes->owner }} 这样我可以使用

'如果(这个)包含Auth::user->id()'...

【问题讨论】:

    标签: php laravel model eloquent foreign-keys


    【解决方案1】:

    检查这一点的一种方法是使用where()first() 收集方法:

    if ($comment->commentLikes->where('user_id', auth()->user()->id)->first())
    

    【讨论】:

      【解决方案2】:
      // This works if $comment->commentLikes returns a collection
      $userLikes = $comment->commentLikes->where('user_id', Auth::user()->id)->all();
      
      if ($userLikes->count() > 0) {
          // Do stuff
      }
      

      【讨论】:

        【解决方案3】:

        选项 1

        使用Laravel collection 你可以这样做:

        $comment->commentLikes->search(function ($item, $key) {
            return $item->user_id == auth()->user()->id;
        });
        

        如果未找到,则返回 false,如果用户在集合中,则返回索引。

        让它漂亮

        但由于您可能会在视图中使用它,因此我会将其打包在 accessor 中,如下所示:

        class Comment extends Model
        {
            public function commentLikes() {
                // relationship defined
            }
        
            public function getHasLikedAttribute()
            {
                // use getRelationValue so it won't load again if it was loaded before
                $comments = $this->getRelationValue('commentLikes');
        
                $isOwner = $comment->commentLikes->search(function ($item, $key) {
                    return $item->user_id == auth()->user()->id;
                });
        
                return $isOwner === false ? false : true;
            }
        }
        

        这样你可以调用$comment->has_liked,如果当前登录的用户在commentLikes关系中,则返回true,如果不是false,则返回。

        【讨论】:

          【解决方案4】:

          用途:

          if ($comment->commentLikes()->where('user_id', auth()->user()->id)->count() > 0)
          

          这比发布的其他答案更有效,因为 where() 和 count() 都适用于查询构建器对象而不是集合

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-01-30
            • 1970-01-01
            • 2013-04-20
            • 2021-12-12
            • 1970-01-01
            • 1970-01-01
            • 2016-06-04
            相关资源
            最近更新 更多