数据库查询到关系



我的查询:

$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);

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

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

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

在控制器中:

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

最新更新