php - Laravel 7与找出谁邀请我建立关系
问题描述
在我的网络应用程序中,每个用户都可以像网络系统一样拥有无限的用户。我可以找到使用用户参考代码注册的用户,但我想知道谁是我的父母并邀请我注册
例如,此代码可以返回使用我的参考代码注册的用户数量:
$users = User::whereNull('user_id')->with('child')->get();
模型:
public function child()
{
return $this->hasMany(User::class)->with('child');
}
我怎样才能知道谁是孩子的父母?就像从树枝到根
User
迁移文件:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('family')->nullable();
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->index()->nullable();
$table->unsignedBigInteger('user_id')->index()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('password');
$table->rememberToken();
$table->softDeletes();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
});
User
模型:
class User extends Authenticatable
{
use Notifiable, SoftDeletes;
protected $guarded = [
'id',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime'
];
public function users()
{
return $this->hasMany(User::class)->with('users');
}
}
解决方案
为了得到父母
{
return $this->belongsTo(User::class, 'user_id');
}
为了得到孩子
{
return $this->hasMany(User::class, 'user_id', 'id');
}
推荐阅读
- arrays - 推迟指向具有灵活数组成员的结构的指针不会“复制”FAM?
- typescript - 如何在 Typescript 中获取枚举大小作为类型
- python - 如何使用python将具有重复值的两个列表组合到字典中
- php - Windows apache虚拟主机的Laravel存储问题
- arm - 在调试模式下擦除 Flash 期间出现 HardFault
- python - 潜在客户评分:更改“新近度”列以反映分数较高的最近日期和分数较低的较晚日期的最佳方法是什么?
- azure-functions - Azure 持久编排 - LockAsync
- node.js - 正则表达式不返回任何值,获取 ip
- node.js - Twilio 函数依赖 - 使用私有节点模块
- javascript - 将项目添加到弹出菜单