Php hasOne关系中的orderBy不';行不通

Php hasOne关系中的orderBy不';行不通,php,laravel,eloquent,laravel-5.5,Php,Laravel,Eloquent,Laravel 5.5,我有一个表(weathers),有几千行,目前有90000多行,每一行都属于一个位置 这个表可以有多个属于一个位置的行,但我仍然只想要一个,即给定位置的最后一个 我的型号位置将此关系定义为: ... public function last_weather() { return $this->hasOne(\App\Weather::class, 'id_location')->orderBy('weathers.id', 'DESC'); } ... 在我的控制器上,我正

我有一个表(
weathers
),有几千行,目前有90000多行,每一行都属于一个位置

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

我的型号
位置
将此关系定义为:

...
public function last_weather() {
    return $this->hasOne(\App\Weather::class, 'id_location')->orderBy('weathers.id', 'DESC');
}
...
在我的控制器上,我正在检索上次天气

...
Location::with(['last_weather'])->findOrfail(1);
...
奇怪的是,直到我在
weather
表中有45000+行,我有3200个位置,并且返回的每个位置的最后记录都在40000+行上(在
weather
表的id 40000和43000+之间)


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

Order by将返回所有行,对于需要使用Group by的每个匹配条件,只返回一行

我从未使用过Laravel,但看看您的代码,我猜您的查询应该是这样的:


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

Order by将返回所有行,对于需要使用Group by的每个匹配条件,只返回一行

我从未使用过Laravel,但看看您的代码,我猜您的查询应该是这样的:


return$this->hasOne(\App\Weather::class,'id\u 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);

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

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

你能把它贴出来吗,请把我在模型上的代码修改成这个吗?好的,但是我如何检索最后一个呢?这将返回第一个,从结尾处删除
DESC
,或将其替换为
ASC
,如果我离开
DESC
,`Column not found:1054未知列'DESC',在'group statement'中,则会出现错误(`你能发布它吗,请将我在模型上的代码调整到这个位置吗?好的,但是我如何检索最后一个?这将返回第一个,要么从末尾删除
DESC
,要么将其替换为
ASC
,如果我离开
DESC
,则会出现错误,`未找到列:1054未知列'groupstatement'中的'DESC'(`我更愿意把它当作一个关系,它更灵活。我可以直接加载,或者选择collumns作为wantI添加的另一种方式。我更愿意把它当作一个关系,它更灵活。我可以直接加载,或者选择collumns作为wantI添加的另一种方式。你可以添加
\DB::enableQueryLog()
在查询之前,然后在查询之后添加
dd(\DB::getQueryLog())
并发布结果?能否在查询之前添加
\DB::enableQueryLog();
,然后在查询之后添加
dd(\DB::getQueryLog())
,并发布结果?