【问题标题】:Laravel 5.5 HasManyThrough RelationshipLaravel 5.5 HasManyThrough 关系
【发布时间】:2018-05-14 10:34:33
【问题描述】:

我有以下数据库:

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 添加一个关系以使Teams 加入。如上所述,如果您为其创建了 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 或其他东西。

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-5.5


    【解决方案1】:

    使用BelongsToMany 关系:

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

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2023-03-09
      • 2018-07-24
      • 2020-10-14
      • 1970-01-01
      • 2018-03-08
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多