Jas*_*nNZ 2 php laravel eloquent laravel-4
我有一个看起来很简单的要求 - 搜索位置等于$ locationId并具有特定服务($ serviceId)的所有个人资料,但我不知道如何添加where条件通过数据透视表查询?
我的模型如下:
class Profile extends Model {
public function services() {
return $this->belongsToMany('Service', 'profile_services', 'profile_id', 'service_id');
}
}
class Service extends Model {}
Run Code Online (Sandbox Code Playgroud)
我想要做的是这样的事情:
$results = Profile::where('location_id', '=', $locationId)->where('services.id', '=', $serviceId)->get();
Run Code Online (Sandbox Code Playgroud)
注意我知道这->where('services.id', '=', $serviceId)是不正确的(我已经把它放在这里以更好地解释我想要实现的目标)但我想知道我会使用Eloquent或DB查询构建器来做到这一点.
你可以过滤关系 whereHas
$results = Profile::where('location_id', '=', $locationId)
->whereHas('services', function($query) use ($serviceId){
$query->where('services.id', '=', $serviceId);
})->get();
Run Code Online (Sandbox Code Playgroud)