【问题标题】:HasManyThrough with another relationship in Laravel 5.2HasManyThrough 与 Laravel 5.2 中的另一个关系
【发布时间】:2016-07-21 10:10:08
【问题描述】:

我有 3 个模型:

锦标赛、类别、团队

锦标赛有很多类别

一个类别有很多团队

表格:

Tournament: Only attributes
Category: id, tournament_id, name
Teams: id, category_id, name

我想通过 $tournament->teams

获得锦标赛的所有球队

我试过了:

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

然后我需要一个我的团队的额外关系:team->category->name;

但是这个 HasManyThrough 的结果没有关系......

有什么想法???

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    Category 模型中:

    public function team ()
    {
      return $this->hasMany('App\Teams');
    }
    

    Teams 模型中:

    public function category ()
    {
       return $this->belongsTo('App\Category', 'category_id');
    }
    

    【讨论】:

      【解决方案2】:

      我觉得应该是这样,试试吧。

      根据 laravel 文档:

      countries
          id - integer
          name - string
      
      users
          id - integer
          country_id - integer
          name - string
      
      posts
          id - integer
          user_id - integer
          title - string
      

      有了这个你可以添加关系:

      public function posts()
          {
              return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');
          }
      

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 2018-10-18
        • 2023-03-09
        • 2016-09-24
        • 2014-03-09
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多