繁体   English   中英

使用数据透视表的Eloquent或Query构建器搜索

[英]Eloquent or Query builder search utilising pivot table

我有一个看起来很简单的要求 - 搜索位置等于$ 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM