laravel从表中获取数据到同一个表的外键

时间:2016-06-07 19:14:58

标签: javascript mysql laravel-5 eloquent

我有两张桌子: 拥有id,group_id和name的团队 具有id,home_team_id,away_team_id,日期和分数的游戏

正如您在我的游戏表中看到的那样,有两个外键(home_team_id和away_team_id)指向同一个表(团队)。 如何用laravel雄辩的方式映射这些关系? 我试过了,但失败了:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    public function group(){
        return $this->belongsTo('App\Group');
    }

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Game extends Model
{
    public function homeTeam(){
        $this->belongsTo('App\Team', 'home_team_id');
    }

    public function awayTeam(){
        $this->belongsTo('App\Team', 'away_team_id');
    }

    public function bets(){
        $this->hasMany('App\Bet');
    }
}

在我看来,我想打电话给home_team-&gt; name和away_team-&gt; name:

<td>{{ $game->homeTeam->name }}</td>
<td>{{ $game->awayTeam->name }}</td>

我收到此错误: 关系方法必须返回类型为Illuminate \ Database \ Eloquent \ Relations \ Relation

的对象

关系方法必须返回Illuminate \ Database \ Eloquent \ Relations \ Relation类型的对象(查看:/home/vagrant/Code/em/resources/views/schedule/index.blade.php)

1 个答案:

答案 0 :(得分:2)

您需要从方法中返回关系。例如:

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

您在团队模型中执行此操作,但不是游戏模型。