hasOne 关系中的 orderBy 不起作用

orderBy in hasOne relation doesn't work

我有一个 table (weathers) 有几千行,目前有 90000 +-,每一行都属于一个位置。

这个 table 可以有多行属于一个位置,但我仍然只想要一个,即给定位置的最后一行。

我的模型 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 table 中有 45000+- 行,我有 3200 个位置,返回的每个位置的最后记录在 40000 +- 行(在 id 40000 和 43000 之间 +-,属于 weathers table)

我已经检查了我的数据库并且我在 80000 上更新了每个位置,但是关系从 40000 返回数据。这甚至不是每个地点的第一个或最后一个天气。

Order by 将 return 所有行,对于您需要使用 Group by

的每个匹配条件仅 return 一行

我从未使用过 Laravel,但查看您的代码我猜您的查询应该如下所示:

return $this->hasOne(\App\Weather::class, 'id_location')->groupBy('weathers.id', 'DESC');

您可以在位置模型中执行此操作

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();

更新

或者您可以调整预加载天气的方式

$location = Location::with([
        'weathers' => function($query) {
            $query->orderBy('id', 'DESC')->first();
        },
    ])
    ->findOrfail(1);