问题
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.
回答1:
Change it to:
App\VehicleModel::find(3)->locations()->whereBetween('time', $range)->get();
回答2:
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);
回答3:
Using relationship method without parenthesis return a collection, use parenthesis to return the relationship where you can add other query methods like whereBetween:
App\VehicleModel::find(3)->location()->whereBetween('time', $range)->get();
来源:https://stackoverflow.com/questions/48156429/laravel-wherebetween-in-relations-not-working