简体   繁体   中英

Laravel 5.5 HasManyThrough Relationship

I have the following database:

teams
-----
id
user_id


users
-----
id


pages
-----
id
user_id
team_id -> (nullable)

So a User can create a Team, and create a Page

Currently, I have the following relationships setup (replace with $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

However, a User can join a team by creating a Page for that team. In this case the pages table will fill in the team_id . Where a page is created and is not for a team, the team_id value will be null

I wanted to add a relationship for User to get the Team s joined. As explained above, you are part of Team if you have created a Page for it.

I have tried the following:

public function teams_joined()
{
    return $this->hasManyThrough(Team::class, FundraisingPage::class);
}

I'm not sure if I should be using a HasManyThrough in this situation

As a backup I have the following:

public function teams_joined()
{
    $uniqueTeamIds = $this->pages()->onlyForTeams()->get()->pluck('id')->unique();
    return Team::whereIn('id', $uniqueTeamIds)->get();
}

where onlyForTeams() is defined on Page as

public function scopeOnlyForTeams($query) {
    return $query->whereNotNull('team_id');
}

But I wanted to use a proper relationship so was wondering if I should be using HasManyThrough or something else for this situation.

Use a BelongsToMany relationship:

public function teams_joined()
{
    return $this->belongsToMany(Team::class, 'pages');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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