繁体   English   中英

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表将填充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');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM