简体   繁体   中英

laravel wherebetween in relations not working

I have two tables in mysql, 1. Vehicles and 2.Locations i am using eloquent relations to define relation of the vehicle table to locations.

here is how my vehicles modle looks.

namespace App;

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

i am trying to run a query that can get me locations of specific vehicle between two given times.

here is what i am trying to do:

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

I was expecting to above query would give me locations between dates which it does when i run without the relation. but when when i do run in a relation i am getting an unexpeted error.

PHP error: Call to a member function whereHas() on null on line 1

Please help me see where i am going wrong.

Thanks in advance.

更改为:

App\VehicleModel::find(3)->locations()->whereBetween('time', $range)->get();

使用不带括号的关系方法返回一个collection ,使用括号返回该关系,您可以在其中添加其他查询方法,例如whereBetween:

App\VehicleModel::find(3)->location()->whereBetween('time', $range)->get(); 

you send query from other relation model location

your query look like this location->location

please check this code

App\VehicleModel::find(3)->locations()->whereBetween('time', $range);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM