Laravel 需要获取每条评论的用户名

Laravel need to get username of each comment

我获取评论者的问题是我在评论时保存了用户 ID,并且我 return post 下面的所有评论,但是当我尝试 return 用户名时同样,Laravel 给出了一个错误,我想这是因为它不知道它应该为哪个用户 ID return 来自用户 table 的用户名。目前评论控制器如下:

$comments = DB::select("Select * from comments where article_id = $articleID");

我得到 $articleID 查看路由,或者从数据库中查找文章内容,我在 comments[=25= 中使用它] table 以及查找属于特定 文章 的评论。但是当我尝试

$commenter = User::where('id', $comments->user_id)->first();

它失败了。我尝试了这种 SQL 命令的几个版本,但没有用。因为它不知道我在说哪个评论者(我猜)。你知道我该怎么做吗?

你必须为此使用 foreach。如果您需要让每个评论都有用户,您应该遍历评论来实现这一点。例如:

$comments = DB::select("Select * from comments where article_id = $articleID");

foreach ($comments as $comment) {
    $commenter = User::where('id', $comment->user_id)->first();
}

如果你想得到所有在文章中有评论的用户,你应该尝试搜索用户并使用建立的关系。 主要思路是这样的。

在用户模型中,您必须设置与评论的关系:

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

然后,您可以使用 whereHas 使用这些关系进行搜索:

$users = User::whereHas('comments', function ($q1) use ($articleId) {
    $q1->where('article_id', $articleId);
})->get();

这样您将获得对这篇文章发表评论的所有用户的列表。

忘记所有这些东西并按照以下步骤操作:

1) 在您的评论模型中添加用户关系:

function user(){
    return $this->belongsTo('App\Models\User','user_id','id');
}

2) 然后得到你的意见如下:

$comments = Comments::where('artical_id',$articleID)->with('user')->get();

3) 然后你会在每个评论对象中得到用户对象。