这是我在Laravel中创建复杂查询的最后一次尝试。我有这个场景需要的3个表:photos, events, countries
。每个活动都有很多或没有照片,每个国家/地区可能有多个带照片的活动。
我的结果显示
PhotosByCountry, EventsByCountry, rContinent, rCountry.
这是运行良好的MySQL本机查询:
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
谁可以帮助我将其翻译成没有DB::raw()
或whereRaw()
的“Laravel查询”构建器。构建该东西的主要问题是子查询。
我为所有表格Models
Photo, Country, Sportevent (for table events (= legacy name), couldn't use Event)
。
感谢您的努力,如果需要,我很乐意提供更多信息。
加成
表:
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
答案 0 :(得分:1)
试试这个:
国家模式
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查询计数)。但我认为这是一个非常好的方法来获得计数。
答案 1 :(得分:0)
完成问题:
由于在Eloquent Query Builder中构建初始查询似乎不可能或太复杂,我在Photo
模型中使用了以下函数(但我可以将它放在任何其他模型中)
public function allCountrysWithPhotos(){
$rawQuery=" 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
ORDER BY rContinent, rCountry";
return DB::select($rawQuery);
}
如果将来需要调整某些内容(索引可能在某个阶段),这对SQLers来说很容易理解。
无论如何,感谢您的努力,我不再会问Eloquent问题了,而是会用原生查询来做。