Laravel 关系,我需要额外的 table 来关联评论吗
Laravel relationship, do I need extra table for relating comments
我需要一些逻辑上的帮助,我有一篇文章 table 和一条评论 table。当用户发表评论时,我将其存储在 table:
中
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();
});
}
我不知道我是否需要添加另一个 table 例如 user_comments
来建立这种关系,这对我来说实际上听起来很愚蠢,但问题我 运行 到这里是我通过基本查询获得评论,例如:
$comments = DB::select("Select * from comments where article_id=$articleID");
但是我很难展示 username
之类的东西,所以我需要两者之间的简单关系,有人知道如何实现它吗?
不,您不需要再添加 table。您只需要定义适当的关系。在 Article
模型中:
public function comments()
{
return $this->hasMany(Comment::class);
}
在Comment
型号中:
public function user()
{
return $this->belongsTo(User::class);
}
要获得 username
使用 nested eager loading:
$article = Article::with('comments.user')->find($articleId);
然后在视图中迭代集合:
@foreach ($article->comments as $comment)
<div>{{ $comment->comment }}</div>
Comment author: {{ $comment->user->username }}
@endforeach
我需要一些逻辑上的帮助,我有一篇文章 table 和一条评论 table。当用户发表评论时,我将其存储在 table:
中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();
});
}
我不知道我是否需要添加另一个 table 例如 user_comments
来建立这种关系,这对我来说实际上听起来很愚蠢,但问题我 运行 到这里是我通过基本查询获得评论,例如:
$comments = DB::select("Select * from comments where article_id=$articleID");
但是我很难展示 username
之类的东西,所以我需要两者之间的简单关系,有人知道如何实现它吗?
不,您不需要再添加 table。您只需要定义适当的关系。在 Article
模型中:
public function comments()
{
return $this->hasMany(Comment::class);
}
在Comment
型号中:
public function user()
{
return $this->belongsTo(User::class);
}
要获得 username
使用 nested eager loading:
$article = Article::with('comments.user')->find($articleId);
然后在视图中迭代集合:
@foreach ($article->comments as $comment)
<div>{{ $comment->comment }}</div>
Comment author: {{ $comment->user->username }}
@endforeach