Php 使用数据透视表进行雄辩或查询生成器搜索

Php 使用数据透视表进行雄辩或查询生成器搜索,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,从表面上看,我有一个简单的要求——搜索所有具有等于$locationId的位置和特定服务($serviceId)的配置文件,但我不确定如何添加通过透视表查询的where条件 我的模型如下: class Profile extends Model { public function services() { return $this->belongsToMany('Service', 'profile_services', 'profile_id', 'servic

从表面上看,我有一个简单的要求——搜索所有具有等于$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)
是不正确的(我把它放在这里是为了更好地解释我试图实现的目标),但我想知道我会使用Elount或DB查询生成器来实现这一点。

您可以过滤与
whereHas的关系

$results = Profile::where('location_id', '=', $locationId)
                  ->whereHas('services', function($query) use ($serviceId){
                      $query->where('services.id', '=', $serviceId);
                  })->get();

试试你想做的,它应该已经起作用了。拉威尔4号有,不,那不行。我得到一个异常-“找不到Column services.id”。即使在添加了
Profile::with(['services'])…
之后,你也可以从我的头顶上查询与
has
的关系,而不是
where
。啊哈,这正是我想要的。干杯@lukasgeiterGreat。谢谢,你今天救了我