数据库一对多,在Laravel中有两个外键字段

Noe*_*tin 15 database laravel eloquent

我一直在尝试定义一些数据库模式来使用laravel框架.我想模拟足球比赛.我想要做的第一步是定义实体关系图,但我发现这(我认为这将是非常微不足道的)在某些方面令人困惑.

首先,显而易见的方法是匹配与两个团队相关,团队与任意数量的匹配相关.所以,我们会有一个"多对多"的关系.

但是多对多关系的实现是有两个表和一个中间表来关联两个实体.我认为这太过分了,当我知道一个Match总是有两个团队而且只有两个列(local_id和visitant_id)和Teams表的外键就足够了.另外,我希望能够做到:

Match::find(1)->local() or Match::find(1)->visitant();
Run Code Online (Sandbox Code Playgroud)

因此,考虑到这一点,我正在实施"一对多"关系,但有了这个,我还有另一个问题.要检索团队已经玩过的所有比赛,我想这样做:

Team::find(1)->matches(); 
Run Code Online (Sandbox Code Playgroud)

但是我不能这样做,因为我只能在eloquent中定义matches()方法时指定一个键列(默认情况下它是team_id,但它应该是visitant_id和local_id).

Noe*_*tin 32

在进一步深入挖掘源代码之后,我发现有一种方法可以实际保存我的数据库模式并实现我想要的(至少在Laravel 4中).我在github上发布了我的问题,Taylor Otwell(框架的创建者)给了我正确答案:https://github.com/laravel/framework/issues/1272

引用他,它应该像这样简单:

class Team extends Eloquent  {
    public function allMatches()
    {
        return $this->hasMany('Match', 'visitant_id')->orWhere('local_id', $this->id);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后...

$team = Team::find(2);
$matches = $team->allMatches;
Run Code Online (Sandbox Code Playgroud)

更新: github链接不起作用,因为laravel不再以这种方式接收错误报告:http://laravel-news.com/2014/09/laravel-removes-github-issues/

  • 当使用`with`时,你渴望加载这种关系.在急切加载的时候,`$ this`中的模型属性还没有被补充,所以`$ this-> id`什么都不返回. (2认同)