它应该是这样的(尚未测试):
$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 个参数传递给将指定连接类型的函数(默认值为“inner”)。join()
如果您使用的是Eloquent并且具有“联盟”模型,那么您也可以在模型上使用joil:
$leagues = League::select('league_name')
->join('countries', 'countries.country_id', '=', 'leagues.country_id')
->where('countries.country_name', $country)
->get();
在本例中,将是扩展常规 Laravel 集合的一个实例,并为您提供比常规集合更多的功能。$leagues
Illuminate\Database\Eloquent\Collection
但是,甚至还有一种更简单的方法可以在不使用联接的情况下编写此内容:
$leagues = League::select('league_name')->whereHas('countries', function($query) use ($country) {
$query->where('country_name', $country);
})->get();
请注意,在此示例中,“国家/地区”不是表名,而是 Eloquent 关系名,因此您需要在使用此方法之前设置关系。
另外,此示例将使用两个查询或一个嵌套查询,而不是使用连接,我不确定;但像这样:SELECT league_name FROM leagues WHERE country_id IN (SELECT id FROM countries WHERE country_name='$country')