gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:12:32 25 4
gpt4 key购买 nike

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

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");

但是我很难显示 username 之类的东西,所以我需要在两者之间建立一个简单的关系,有人知道如何实现吗?

最佳答案

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com