I am trying to filter jobs which have location distance less than certain limit as follows. Job
and Location
have many-many relation.
Job.php
class Job extends Model
{
protected $table = 'jobs';
protected $fillable = ['company_id', 'role_id', 'job_title'];
public function location()
{
return $this->belongsToMany('App\Pincode', 'job_pincodes', 'job_id', 'location_id');
}
}
Pincode.php
class Pincode extends Model
{
protected $table = 'pincodes';
protected $fillabe = ['location', 'pincode', 'state', 'district'];
public function jobs()
{
return $this->belongsToMany('App\Job');
}
}
The problem is that I don't know how to access each row of relationship inside whereHas
. Please help.
$user_lat = 28.7041;
$user_long = 77.1025;
$distance = 12;
$result = Job::whereHas('location',function($query)
use($user_lat,$user_long,$distance){
// I don't know how to access location's column values to calculate distance
$query->whereRaw('3959 * acos( cos( radians(?) ) * cos( radians(?) ) * cos( radians(?) - radians(?) ) + sin( radians(?) ) * sin(radians(?)) ) <=?', array($location->lati, $user_lat, $location->longi, $user_long, $location->lati,$user_lat, $distance));
}
via Nitesh Verma