首页 > 解决方案 > 无法在同一模型上创建一对多关系

问题描述

我想sponsors在我的网站上创建用户。我使用与关系相同的模型。

用户.php(模型):

public function sponsor(): HasMany
{
    return $this->hasMany(self::class, 'sponsored_id', 'sponsor_id');
}

public function sponsored(): BelongsTo
{
    return $this->BelongsTo(self::class, 'sponsor_id', 'sponsored_id');
}

赞助商行:

Schema::table('users', function (Blueprint $table) {
    $table->foreignId('sponsor_id')->nullable();
    $table->foreignId('sponsored_id')->nullable();
});

我的用户播种机:

$sponsor = User::factory()->create(['name' => 'sponsor']);

$sponsor->sponsor()->save(
    User::factory()->make()
);

标签: laravel

解决方案


根据您的评论,您正试图从赞助商那里检索一条记录,所以它应该是

$sponsor->sponsor()->first()

推荐阅读