首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查集合是否包含值

问检查集合是否包含值
EN

Stack Overflow用户
提问于 2017-01-19 23:57:52
回答 4查看 1.1K关注 0票数 2

我已经设置了关系(我想是正确的)..我有3个表,用户,评论和评论的点赞表。

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

代码语言:javascript
复制
[{"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代表类似的所有者。

现在我想检查这个集合是否有经过身份验证的用户,换句话说,当前用户是否喜欢这个评论。有没有比使用for循环更好的方法呢?也许是像{{ $comment->commentLikes->owner }}这样的东西,这样我就可以使用

‘如果(此)包含Auth::user->id()'...

EN

回答 4

Stack Overflow用户

发布于 2017-01-20 00:02:23

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

代码语言:javascript
复制
if ($comment->commentLikes->where('user_id', auth()->user()->id)->first())
票数 0
EN

Stack Overflow用户

发布于 2017-01-20 00:02:38

代码语言:javascript
复制
// This works if $comment->commentLikes returns a collection
$userLikes = $comment->commentLikes->where('user_id', Auth::user()->id)->all();

if ($userLikes->count() > 0) {
    // Do stuff
}
票数 0
EN

Stack Overflow用户

发布于 2017-01-20 00:11:33

选项1

使用Laravel collection,您可以这样做:

代码语言:javascript
复制
$comment->commentLikes->search(function ($item, $key) {
    return $item->user_id == auth()->user()->id;
});

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

让它变得很漂亮

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

代码语言:javascript
复制
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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41746260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档