laravel - 无法在同一模型上创建一对多关系
问题描述
我想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()
);
解决方案
根据您的评论,您正试图从赞助商那里检索一条记录,所以它应该是
$sponsor->sponsor()->first()
推荐阅读
- javascript - 检查 json 对象数组是另一个 json 对象数组的子集
- python - 基于变量的绘图背景形状
- c++ - 在使用 LLVM 解释器时查找变量名
- xamarin - 如何根据移动设备的方向更改(感知)Xamarin 表单的方向?
- eclipse - Maven/Tycho - 如何基于相同的依赖项构建可执行 jar 和 Eclipse 应用程序?
- angular - Angular 6,路由器导航不会加载组件视图,但 url 会发生变化
- javascript - NodeJS 在正确的时间获取变量的问题 [npm like module]
- .htaccess - .htaccess 中的 mod_rewrite 规则跳过 TYPO3 中的 URI
- java - 我用什么命令来解决这个问题?
- python - 在 python3 中读取 zip 文件,与 python2 相同