我在这里需要一些逻辑帮助,我有一个文章表和一个评论表。当用户评论时,我将其存储在表中:
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->string('comment');
$table->integer('article_id');
$table->timestamps();
});
}
我不知道是否需要添加另一个表,例如 user_comments
来建立这种关系,这对我来说实际上听起来很愚蠢,但我在这里遇到的问题是我使用基本查询获取评论,例如:
$comments = DB::select("Select * from comments where article_id=$articleID");
但是我很难显示用户名
之类的东西,所以我需要之间有一个简单的关系,有人知道如何实现它吗?
最佳答案
不,您不需要添加另一个表。您只需要定义适当的关系。在 Article
模型中:
public function comments()
{
return $this->hasMany(Comment::class);
}
在注释
模型中:
public function user()
{
return $this->belongsTo(User::class);
}
要获取用户名
,请使用 nested eager loading :
$article = Article::with('comments.user')->find($articleId);
然后在 View 中迭代集合:
@foreach ($article->comments as $comment)
<div>{{ $comment->comment }}</div>
Comment author: {{ $comment->user->username }}
@endforeach
关于mysql - Laravel 关系,我需要额外的表格来关联评论吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47979122/