dqp21271
2014-12-27 01:15
浏览 48
已采纳

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

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);
                      })->get();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题