这是我最后一次尝试在 Laravel 中创建复杂查询。对于此场景,我需要 3 个表:photos、events、countries
。每个事件有很多照片或没有照片,每个国家可能有多个带有照片的事件。
我的结果显示
PhotosByCountry, EventsByCountry, rContinent, rCountry.
下面是运行良好的 MySQL native 查询:
SELECT SUM( allPhotos ) AS PhotosByCountry,
COUNT( temp.Land ) AS EventsByCountry,
rContinent,
temp.Land AS rCountry
FROM (
SELECT e.country AS Land, COUNT( p.id ) AS allPhotos, c.continent AS rContinent
FROM `photos` p
INNER JOIN `events` e ON e.id = p.eventID
INNER JOIN countries c ON e.country = c.country
GROUP BY p.eventID
)temp
GROUP BY rCountry
谁能帮我把它翻译成 Laravel 查询构建器而不需要 DB::raw()
或 whereRaw()
。我构建那个东西的主要问题是子查询。
我得到了所有表格的模型
:照片、国家/地区、Sportevent(对于表格事件(= 旧名称),无法使用事件)
。
感谢您的努力,如果需要,我很乐意提供更多信息。
添加
表格:
events
id | name | country ... has more columns of course
1 | Eventname 1 | France
2 | Eventname 2 | Switzerland
3 | Eventname 3 | France
photos
id | eventID | path ...
1 | 2 | .....
2 | 1 | .....
3 | 2 | .....
4 | 3 | .....
5 | 3 | .....
6 | 2 | .....
countries
id | country | continent (or geographical Region) ...
1 | France | Europe
2 | Switzerland | Europe
3 | Germany | Europe
4 | United States| North America
5 | Australia | Oceania
6 | .....
Result
PhotosByCountry | EventsByCountry | rContinent | rCountry
3 | 2 | Europe | France
3 | 1 | Europe | Switzerland
最佳答案
试试这个:
国家模式
protected function photosCount()
{
return $this->hasManyThrough('photos', 'events', 'country', 'event_id')
->groupBy('countries.country')
->count();
}
public function getPhotosCount() {
return $this->photosCount ? $this->photosCount->count : 0;
}
protected function eventsCount()
{
return $this->hasMany('events', 'country', 'event_id')
->groupBy('countries.country')
->count();
}
public function getEventsCount() {
return $this->eventsCount ? $this->eventsCount->count : 0;
}
像这样访问它:
$countries = Country::with('photosCount', 'eventsCount')->get();
$countries->first()->getPhotosCount();
$countries->first()->getEventsCount();
代码未经测试。
来源:http://laravel.io/forum/05-03-2014-eloquent-get-count-relation
这可能会生成 3 个 sql 查询而不是 1 个(一个针对国家/地区 + 2 个带有计数的 WHERE IN 查询)。但我认为这是获得计数的一种非常好的方式。
关于mysql - 复杂查询 3 个表,在 Laravel 中有 2 个 INNER JOIN、1 个子查询、2 个 Group By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28984278/