laravel wherebetween in relations not working

ⅰ亾dé卋堺 提交于 2020-01-05 07:18:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!