Laravel关系-选择刀片中具有相同列值的行

时间:2018-08-07 12:39:05

标签: laravel relationships

比方说,我有一条带有很多评论的帖子,并且在我的帖子模型中正确定义了$post->comments关系。注释具有名为confirmed的列,其值为01。如何在刀片模板中选择已确认的行(行的确认值为1)?

2 个答案:

答案 0 :(得分:0)

这可以帮助您 在您的帖子模型中

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

public function confirmedComments()
{
    return $this->comments()->whereConfirmed(1);
}

并通过您的控制器

$comments = $post->confirmedComments;

如果在刀片中,您想要选择已确认的评论,那么使用它很容易

@if($comment->confirmed)
    //confirmed comment
@else
   //
@endif

希望这会有所帮助!

答案 1 :(得分:0)

有很多方法可以做到这一点。

如果您已经加载了comments切入点,则可以在where()集合上使用comments方法:

$confirmedComments = $post->comments->where('confirmed', 1);

这将遍历集合中的所有注释,仅返回已确认的注释。

如果没有现有集合,则可以将where子句添加到关系查询中。这样,您只会从数据库中获得已确认的评论,而不会浪费资源来检索和为未使用的评论建立模型

$confirmedComments = $post->comments()->where('confirmed', 1)->get();

另一种选择是为已确认的评论创建新关系,这样您就可以急于加载新关系:

public function comments()
{
    return $this->hasMany(Comments::class);
}

public function confirmedComments()
{
    return $this->comments()->where('confirmed', 1);
}

$confirmedComments = $post->confirmedComments;