我已经设置了关系(我想是正确的)..我有3个表,用户,评论和评论的点赞表。
在我的刀片中,我可以使用以下命令访问{{ $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代表类似的所有者。
现在我想检查这个集合是否有经过身份验证的用户,换句话说,当前用户是否喜欢这个评论。有没有比使用for循环更好的方法呢?也许是像{{ $comment->commentLikes->owner }}这样的东西,这样我就可以使用
‘如果(此)包含Auth::user->id()'...
发布于 2017-01-20 00:02:23
检查这种情况的一种方法是使用where()和first()收集方法:
if ($comment->commentLikes->where('user_id', auth()->user()->id)->first())发布于 2017-01-20 00:02:38
// This works if $comment->commentLikes returns a collection
$userLikes = $comment->commentLikes->where('user_id', Auth::user()->id)->all();
if ($userLikes->count() > 0) {
// Do stuff
}发布于 2017-01-20 00:11:33
选项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。
https://stackoverflow.com/questions/41746260
复制相似问题