繁体   English   中英

LARAVEL 怎么隐藏一些关系记录?

[英]LARAVEL how to hide some of the relationship records?

例如,您有Post & Comments并且Post可以有多个评论,但给定的用户只能看到特定的评论。 如何做到这一点?

假设我们有一个用户、帖子和评论,并且给定的用户只能看到他们的朋友创建的评论。

// Post.php
public function comments()
{
    return $this->hasMany(Comment::class);
}

// User.php
public function friends()
{
    return $this->hasMany(Friend::class);
}

// CommentPolicy.php
public function view(User $user, Comment $comment)
{
    return $user->friends->pluck('id')->contains($comment->created_by_id);
}

那么,当我们运行$post->comments时——我们可以在每条记录上运行该策略吗?

您可以使用全局范围局部范围来定义约束集:

 /**
 * Scope a query to only include popular comments.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopePopular($query)
{
    return $query->where('votes', '>', 100);
}

用法:

$post->comments()->popular()->get();

您可以使用此问题的其他答案中提到的范围。

或者您可以通过以下方式在关系本身中使用过滤器:

public function comments()
{
    return $this->hasMany(Comment::class)->where('is_visible', true);
}

它将获取针对is_visible设置为true的帖子的所有评论

希望这会帮助你。

最好的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM