Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Laravel relationship,我是否需要额外的表格用于相关评论_Mysql_Laravel_Laravel 5.4_Relationship - Fatal编程技术网

Mysql Laravel relationship,我是否需要额外的表格用于相关评论

Mysql Laravel relationship,我是否需要额外的表格用于相关评论,mysql,laravel,laravel-5.4,relationship,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->int

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

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\u comments
,或者为了建立这种关系,它实际上听起来很愚蠢,但我在这里遇到的问题是,我通过一个基本查询获得注释,如:

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

但是,我很难显示
用户名
和其他内容,因此我需要一个简单的关系,任何人都知道如何实现它吗?

不,您不需要添加另一个表。你只需要定义适当的关系。在
文章中
模型:

public function comments()
{
    return $this->hasMany(Comment::class);
}
public function user()
{
    return $this->belongsTo(User::class);
}
注释中
模型:

public function comments()
{
    return $this->hasMany(Comment::class);
}
public function user()
{
    return $this->belongsTo(User::class);
}
要获取
用户名
请使用:

然后在视图中迭代集合:

@foreach ($article->comments as $comment)
    <div>{{ $comment->comment }}</div>
    Comment author: {{ $comment->user->username }}
@endforeach
@foreach($article->comments as$comment)
{{$comment->comment}
评论作者:{{$Comment->user->username}
@endforeach

那太好了,但是我能不能在通过
文章后,只做
@foreach($article->comments as$comment)
然后
$comment->user->username
?顺便问一下,你是说
文章::with
?@Nikonah是的,我是说
文章::with
,谢谢,修复了。如果不将
用于()
$comment->user->username
将生成N个附加查询。所以,如果加载100条注释,Laravel将生成101条对DB的查询,而不是2.0条。它按预期工作!我认为你的答案是正确的。但有一个小问题。假设我有另一个表,其中
id
user
id相同,我调用id
userprofil
,我想访问该表而不是
user
表,但每次我尝试访问时,forigen键和内容都会出错,任何关于这方面的意见都会对我有很大帮助。@Nikonah这实际上取决于
评论
用户
配置文件
模型之间的关系。如果您无法解决此新问题,请创建一个新问题并发布所有相关代码(关系、查询)。