应该是这样的(未测试):
$leagues = DB::table('leagues')
->select('league_name')
->join('countries', 'countries.country_id', '=', 'leagues.country_id')
->where('countries.country_name', $country)
->get();
$leagues 将是 Illuminate\Support\Collection 对象的实例,因此您可以使用 foreach 对其进行迭代。
您可以将第 5 个参数传递给 join() 函数,该函数将指定连接类型(默认为“内部”)。
如果您使用 Eloquent 并拥有“联盟”模型,那么您也可以在模型上使用 join:
$leagues = League::select('league_name')
->join('countries', 'countries.country_id', '=', 'leagues.country_id')
->where('countries.country_name', $country)
->get();
在这种情况下,$leagues 将是 Illuminate\Database\Eloquent\Collection 的一个实例,它扩展了常规 Laravel 集合并为您提供比常规集合更多的功能。
但是,还有一种更简单的方法可以在不使用连接的情况下编写此代码:
$leagues = League::select('league_name')->whereHas('countries', function($query) use ($country) {
$query->where('country_name', $country);
})->get();
请注意,在此示例中,“国家/地区”不是表名,而是 Eloquent relationship name,因此您需要在使用此方法之前设置您的关系。
另外,这个例子不是使用join,而是使用两个查询,或者一个嵌套查询,我不确定;但是是这样的:SELECT league_name FROM leagues WHERE country_id IN (SELECT id FROM countries WHERE country_name='$country')