[英]orderBy in hasOne relation doesn't work
我有一張桌子( weathers
),上面有幾千行,目前90000 +-,每行都屬於一個位置。
該表可以有多個行屬於一個位置,但是我仍然只想要一個,給定位置的最后一行。
我的模型Location
具有以下關系定義:
...
public function last_weather() {
return $this->hasOne(\App\Weather::class, 'id_location')->orderBy('weathers.id', 'DESC');
}
...
在我的控制器上,我正在檢索last_weather
例如:
...
Location::with(['last_weather'])->findOrfail(1);
...
奇怪的是,直到我在weather
表中有45000 +-行,我有3200個位置,並且返回的每個位置的最后記錄在40000 +-行(id為40000到43000 +-,介於weathers
表)
我已經檢查了數據庫,並在80000上更新了每個位置,但是該關系正在從40000上返回數據。 這甚至不是每個位置的第一個或最后一個天氣。
您可以在位置模型中執行此操作
public function weathers()
{
return $this->hasMany(\App\Weather::class, 'id_location');
}
public function lastWeather()
{
return $this->weathers()->latest()->first();
}
然后在您的控制器中
$location = Location::findOrfail(1);
然后您就可以像這樣訪問最近的天氣
$location->lastWeather();
UPDATE
或者,您可以調整自己急於加載天氣的方式
$location = Location::with([
'weathers' => function($query) {
$query->orderBy('id', 'DESC')->first();
},
])
->findOrfail(1);
Order by將返回所有行,對於您需要使用Group by的每個匹配條件,僅返回一行
我從未使用過Laravel,但是在查看您的代碼時,我猜您的查詢應如下所示:
return $this->hasOne(\\App\\Weather::class, 'id_location')->groupBy('weathers.id', 'DESC');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.