Laravel 如何将系统中的注释表与主题和用户关联?

Laravel 如何将系统中的注释表与主题和用户关联?,laravel,laravel-7,Laravel,Laravel 7,我正在编写一个API,在这个API中有主题、用户和注释表。我链接了用户和主题,但无法链接我的评论表。你能帮我吗 评论迁移 Schema::create('comments', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('user_id')->unsigned(); $table->bigInteger('post

我正在编写一个API,在这个API中有主题、用户和注释表。我链接了用户和主题,但无法链接我的评论表。你能帮我吗

评论迁移

Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->bigInteger('post_id')->unsigned();
        $table->longText('description');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        $table->timestamps();
    });
我有一个帖子,用户,评论模型和控制器


我正在为一个类似Instagram的移动应用程序编写api。我是拉威尔的新手。我如何建立这种联系?

你需要看看有说服力的关系:

在您的评论示例中,您需要一个
BelongsTo
关系,用于用户和在您的评论模型上发布

在Posts和Users模型中,您需要
具有许多关系

示例:

class Comment extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'description'
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
}

class User extends Model
{
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }

    public function post(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    protected $fillable = [
        'user_id'
    ];

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
我使用的一个很好的经验法则是,当一个模型包含对另一个模型的引用时,您需要一个
belongsTo
关系,就像在注释模型中一样,它既有
用户id
又有
发布id

这不是解决问题的完整指南,而是正确方向的提示。有很多拉威尔魔术在幕后进行,这使得这项工作的开箱即用