如何将系统中的评论 table 与主题和用户相关联?

How can I associate the Comment table in a system with subjects and users?

我正在写一个 API,我在这个 API 中有主题、用户、评论 table。我 link 编辑了用户和主题,但无法 link 我的评论 table。你能帮帮我吗?

评论迁移

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();
    });

我有一个 Post、用户、评论模型和控制器。

我正在写 api 到一个像 Instagram 一样工作的移动应用程序。我是 Laravel 的新手。如何建立关联?

你需要看看Eloquent关系:https://laravel.com/docs/7.x/eloquent-relationships

在您的评论示例中,您需要 BelongsTo User 关系和 Post Comments 模型。

在 Post 和用户模型上,您需要 HasMany 关系。

示例:

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 关系,就像 Comment 模型的情况一样,它同时具有 user_idpost_id.

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