Laravel 关系 - 在 blade 中具有相同列值的 Select 行

Laravel Relationships - Select rows with same column value in blade

假设我有一个包含许多评论的 post,并且我在我的 post 模型中正确定义了 $post->comments 关系。评论有一个名为 confirmed 的列,其值为 01。如何在我的 blade 模板中 select 确认(确认值为 1 的行)行?

这可以帮助你 在您的 Post 模型中

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

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

并从您的控制器

$comments = $post->confirmedComments;

如果在 blade 中,你想要 select 确认的评论,使用

很容易做到
@if($comment->confirmed)
    //confirmed comment
@else
   //
@endif

希望对您有所帮助!

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

如果您已经预先加载了 comments,那么您可以在 comments 集合上使用 where() 方法:

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

这将遍历集合中的所有评论,并且只有 return 已确认的评论。

如果您没有现有的集合,您可以将 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;