mysql - Laravel 关系,我需要额外的表格来关联评论吗

标签 mysql laravel laravel-5.4 relationship

我在这里需要一些逻辑帮助,我有一个文章表和一个评论表。当用户评论时,我将其存储在表中:

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/

相关文章:

mysql - 从 MySQL 中的多个表中检索记录

mysql - 如何在数据库中保存婚姻关系

php - Laravel 5.4 升级——违反完整性约束——列不能为空

php laravel 从过去一周的数据库中获取数据

php - Laravel 使用软删除显示关系数据

php - 如何为 laravel 设置默认的 postgresql 架构?

php - 为什么这个页面添加号码和重定向失败?

mysql - 显示组中的用户数,甚至是空组

php - 在 Laravel 5 Collection 中,如何返回对象数组而不是数组数组?

mongodb - $lookup 当外部字段是数组时