Laravel Inner Join?

2022-08-30 15:06:49

我有一个PHP后端,我目前正在更改以使用Laravel框架。但是,我不太确定Laravel内部连接是如何工作的。

我试图移动到Laravel的SQL查询是:

"SELECT leagues.league_name FROM leagues INNER JOIN countries on leagues.country_id = countries.country_id WHERE countries.country_name = '$country' "

有人能够解释Laravel Joins是如何工作的吗?

如果这个问题不合适,请道歉。


答案 1

它应该是这样的(尚未测试):

$leagues = DB::table('leagues')
    ->select('league_name')
    ->join('countries', 'countries.country_id', '=', 'leagues.country_id')
    ->where('countries.country_name', $country)
    ->get();

$leagues将是对象的实例,因此您可以使用例如对其进行迭代。Illuminate\Support\Collectionforeach

您可以将第 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 集合的一个实例,并为您提供比常规集合更多的功能。$leaguesIlluminate\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')


答案 2

这是非常直接的,也许使用查询生成器查看您的查询会更有意义。

$results = DB::table('leagues')
    ->join('countries', 'leagues.country_id', '=', 'countries.country_id')
    ->where('countries.country_name', $country)
    ->get();

推荐