[英]laravel one to one and one to many eloquent relationship best practice
想象以下要求:
足球队有三种类型的用户:老板、导师和足球运动员。
每个足球运动员都属于其中一支导师球队,而另一方面,导师可以指导多支球队。
我检测到团队和足球运动员之间存在一对一的关系,并且在用户 model 中定义的导师和团队之间存在许多关系,如下所示:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
public function team()
{
return $this->hasOne(Teams::class);
}
public function teams()
{
return $this->hasMany(Teams::class, 'mentor_id');
}
}
并在团队 model
class Teams extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class, 'team_id'); // where team_id is a nullable column in users table for who has soccer player role
}
public function mentors()
{
return $this->belongsTo(User::class);
}
}
我正在寻找制作模型和 eloquent 关系的最佳解决方案
对于我看到你的问题,我可以这样做。
团队表
| id | mentor_id | owner_id |
|---- |-----------| ---------|
用户表
| id | team_id |
|---- |---------|
team_id can be null for mentor and owner
团队模式
class Team extends Model
{
use HasFactory;
public function players()
{
return $this->hasMany(User::class); // where team_id is not null in users table for players
}
public function mentor()
{
return $this->belongsTo(User::class,'mentor_id'); //team mentor
}
public function owner()
{
return $this->belongsTo(User::class,'owner_id'); //team owner
}
}
用户模式
class User extends Model
{
use HasApiTokens, HasFactory, Notifiable;
public function ownedTeams()
{
return $this->hasMany(Team::class,'owner_id'); // teams the user owns if owner
}
public function mentoredTeams()
{
return $this->hasMany(Team::class,'mentor_id'); //teams the user mentors if mentor
}
public function team()
{
return $this->belongsTo(Team::class); //team the user plays for if soccer player
}
}
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.