Laravel 5.5 HasManyThrough 关系
Laravel 5.5 HasManyThrough Relationship
我有以下数据库:
teams
-----
id
user_id
users
-----
id
pages
-----
id
user_id
team_id -> (nullable)
因此用户可以创建团队,并创建页面
目前,我有以下关系设置(替换为$this
)
teams_owned() -> $user->hasMany(Team::class); // Teams a user owns
pages() -> $user->hasMany(Page::class); // Page a user created
user() -> $team->belongsTo(User::class); // User who created team
user() -> $page->belongsTo(User::class); // User who created the Page
但是,用户可以通过为该团队创建主页来加入该团队。在这种情况下,pages
table 将填充 team_id
。如果创建的页面不是团队的,team_id
值将是 null
我想为 User
添加一个关系以加入 Team
。如上所述,如果您为其创建了 Page
,那么您就是 Team
的一部分。
我试过以下方法:
public function teams_joined()
{
return $this->hasManyThrough(Team::class, FundraisingPage::class);
}
我不确定在这种情况下是否应该使用 HasManyThrough
作为备份,我有以下内容:
public function teams_joined()
{
$uniqueTeamIds = $this->pages()->onlyForTeams()->get()->pluck('id')->unique();
return Team::whereIn('id', $uniqueTeamIds)->get();
}
其中 onlyForTeams()
在 Page
上定义为
public function scopeOnlyForTeams($query) {
return $query->whereNotNull('team_id');
}
但我想使用适当的关系,所以想知道我是否应该使用 HasManyThrough
或其他东西来应对这种情况。
使用 BelongsToMany
关系:
public function teams_joined()
{
return $this->belongsToMany(Team::class, 'pages');
}
我有以下数据库:
teams
-----
id
user_id
users
-----
id
pages
-----
id
user_id
team_id -> (nullable)
因此用户可以创建团队,并创建页面
目前,我有以下关系设置(替换为$this
)
teams_owned() -> $user->hasMany(Team::class); // Teams a user owns
pages() -> $user->hasMany(Page::class); // Page a user created
user() -> $team->belongsTo(User::class); // User who created team
user() -> $page->belongsTo(User::class); // User who created the Page
但是,用户可以通过为该团队创建主页来加入该团队。在这种情况下,pages
table 将填充 team_id
。如果创建的页面不是团队的,team_id
值将是 null
我想为 User
添加一个关系以加入 Team
。如上所述,如果您为其创建了 Page
,那么您就是 Team
的一部分。
我试过以下方法:
public function teams_joined()
{
return $this->hasManyThrough(Team::class, FundraisingPage::class);
}
我不确定在这种情况下是否应该使用 HasManyThrough
作为备份,我有以下内容:
public function teams_joined()
{
$uniqueTeamIds = $this->pages()->onlyForTeams()->get()->pluck('id')->unique();
return Team::whereIn('id', $uniqueTeamIds)->get();
}
其中 onlyForTeams()
在 Page
上定义为
public function scopeOnlyForTeams($query) {
return $query->whereNotNull('team_id');
}
但我想使用适当的关系,所以想知道我是否应该使用 HasManyThrough
或其他东西来应对这种情况。
使用 BelongsToMany
关系:
public function teams_joined()
{
return $this->belongsToMany(Team::class, 'pages');
}