我正在尝试过滤位置距离小于特定限制的作业,如下所示。 Job
和Location
有很多关系。
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','lati','longi'];
public function jobs() {
return $this->belongsToMany('App\Job');
}
}
问题是我不知道如何访问whereHas
内的每一行关系。请帮忙。
$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
$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));
})->get();
答案 0 :(得分:0)
只需使用with()
,然后通过query
$result = Job::with('location').whereHas('location',function(query)
use($user_lat,$user_long,$distance) {
// I don't know how to access $location
$query->whereRaw('3959 * acos( cos( radians(?) ) * cos( radians(?) ) * cos( radians(?) - radians(?) ) + sin( radians(?) ) * sin(radians(?)) ) <=?', array($query->location->lati, $user_lat, $query->location->longi, $user_long, $query->location->lati,$user_lat, $distance));
})->get();