数据库查询关系

时间:2018-08-27 14:29:40

标签: laravel eloquent relationship

我的查询:

$data = DB::table('countries')
        ->leftJoin('matches', function ($join) {
            $join->on('matches.hometeam', '=', 'countries.id')
            ->orOn('matches.awayteam', '=' ,'countries.id');
        })
        ->where('countries.id', $id)->get();

        return dd($data);

如何使用关系获得相同的结果?

1 个答案:

答案 0 :(得分:1)

在您的模型中(还需要一个匹配模型):

<?php
class Country extends Model {
  public function matches() {
    return $this->hasMany(App\Matches::class, ['hometeam', 'awayteam'], 'id');
  }
}

在您的控制器中:

$countrys = Countrys::where('id', $id)->get()
foreach($countrys as $country) {
  var_dump($country->matches);
}
die();