laravel wherebetween 在关系中不起作用

Max*_*med 2 php laravel eloquent laravel-eloquent

我在 mysql 中有两个表,1. Vehicles 和 2.Locations 我使用雄辩的关系来定义车辆表与位置的关系。

这是我的车辆模型的外观。

namespace App;

use Illuminate\Database\Eloquent\Model;
class VehicleModel extends Model {
function locations(){
        return $this->hasMany("App\locations", "vehicle_id", "id");
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试运行一个查询,可以让我在两个给定时间之间获取特定车辆的位置。

这是我想要做的:

App\VehicleModel::find(3)->location->whereBetween('locations.time', $range); 
Run Code Online (Sandbox Code Playgroud)

我期待上面的查询会给我日期之间的位置,当我在没有关系的情况下运行时它会这样做。但是当我在关系中运行时,我收到了一个意外错误。

PHP 错误:在第 1 行调用成员函数 whereHas() on null

请帮我看看我哪里出错了。

提前致谢。

Ale*_*nin 5

将其更改为:

App\VehicleModel::find(3)->locations()->whereBetween('time', $range)->get();
Run Code Online (Sandbox Code Playgroud)