2014-12-27 01:15
浏览 48


I have what appears on the face of it to be a simple requirement - search for all Profiles that have a location equal to $locationId and have a specific service ($serviceId), but I'm not sure how to add a where condition that queries via a pivot table?

My models are as follows:

class Profile extends Model {

    public function services() {
        return $this->belongsToMany('Service', 'profile_services', 'profile_id', 'service_id');


class Service extends Model {}

What I want to do is something along the lines of this:

$results = Profile::where('location_id', '=', $locationId)->where('services.id', '=', $serviceId)->get();

Note I'm aware that ->where('services.id', '=', $serviceId) is incorrect (I've put it here to better explain what I'm trying to achieve) but I'd like to know I'd do this using either Eloquent or the DB query builder.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duancongduo4109 2014-12-27 10:13

    You can filter relations with whereHas

    $results = Profile::where('location_id', '=', $locationId)
                      ->whereHas('services', function($query) use ($serviceId){
                          $query->where('services.id', '=', $serviceId);
    解决 无用
    打赏 举报

相关推荐 更多相似问题