我表面上看起来是一个简单的要求-搜索位置等于$ locationId并具有特定服务($ serviceId)的所有配置文件,但是我不确定如何添加where条件通过数据透视表查询?
我的模型如下:
class Profile extends Model {
public function services() {
return $this->belongsToMany('Service', 'profile_services', 'profile_id', 'service_id');
}
}
class Service extends Model {}
我想做的是遵循以下思路:
$results = Profile::where('location_id', '=', $locationId)->where('services.id', '=', $serviceId)->get();
注意我知道
->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();
关于php - 使用枢轴表进行 Eloquent 或查询构建器搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663560/