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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真