Laravel通过表格雄辩的关系

时间:2015-06-06 20:59:03

标签: laravel laravel-4 orm eloquent laravel-5

我有以下数据库表:

用户

  • id
  • 名称

季节

  • ID
  • 名称

  • ID
  • 名称

  • ID
  • season_d
  • TEAM_ID
  • USER_ID

夹具

  • ID
  • season_id
  • home_team_id
  • away_team_id

我的问题是,我如何获得团队所属的某个用户?例如,我可能想要执行以下操作:

$fixture = Fixture::find(1);

echo $fixture->homeTeam->user->name;

我的模特看起来像这样:

灯具型号

class Fixture extends Eloquent{

    public function season(){

        return $this->belongsTo('Season');

    }

    public function homeTeam(){

        return $this->belongsTo('Team', 'home_team_id');

    }

    public function awayTeam(){

        return $this->belongsTo('Team', 'away_team_id');

    }

}

团队模型

class Team extends Eloquent{

    public function standings(){

        return $this->hasMany('Standing');

    }

    public function seasons(){

        return $this->belongsToMany('Season', 'Standings');

    }

    public function users(){

        return $this->belongsToMany('User', 'Standings');

    }

}

季节模型

class Season extends Eloquent{

    public function standings(){

        return $this->hasMany('Standing');

    }

    public function teams(){

        return $this->belongsToMany('Team', 'Standings');

    }

    public function users(){

        return $this->belongsToMany('User', 'Standings');

    }

    public function fixtures(){

        return $this->hasMany('Fixture');

    }

}

我认为我需要向Team模型添加用户函数,而不是当前用户函数,但我无法找出正确的关系方式。任何一个赛季,一支球队只有一名用户。任何帮助将不胜感激,谢谢!

更新

我在Fixture模型中添加了以下关系,这使我可以让用户和团队通过排名表:

public function homeTeamStanding(){

    return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'home_team_id', 'team_id')->where('season_id', $this->season_id);

}

public function awayTeamStanding(){

    return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'away_team_id', 'team_id')->where('season_id', $this->season_id);

}

这个问题是我无法在急切加载时使用它,所以运行了很多查询,因为当我尝试加载它们时,$ this-> season_id为null。当然有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我用连接代替了上面的内容,这样我就可以急切加载,从而减少查询次数!<​​/ p>

public function homeTeamStanding(){

    return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'home_team_id', 'team_id')
        ->join('fixtures', 'fixtures.season_id', '=', 'standings.season_id');

}

public function awayTeamStanding(){

    return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'away_team_id', 'team_id')
        ->join('fixtures', 'fixtures.season_id', '=', 'standings.season_id');

}