Laravel根据连接表列的条件获取连接数据

时间:2018-09-21 06:15:48

标签: php laravel-5 eloquent

大家好,我正在使用laravel5.5 我有两个表Users和Services

  

用户表

  1. id
  2. 名称
  3. 电子邮件
  4. 密码
  5. 地址
  6. 城市
  7. 国家
  8. 邮政编码
  

服务表

  1. id
  2. User_id
  3. 名称
  4. 说明
  5. 价格
  

在用户模型中

public function services()
{
    return $this->hasMany('App\Service');
}
  

服务模式

public function user()
{
    return $this->belongsTo('App\User');
}

现在在控制器中,我需要用户->邮政编码= 20006的所有服务 我怎么才能得到它 我已经尝试过以下代码

$services = Service::with('user')->where('user->zipcode', '20006')->get();

但这没用。

先谢谢。 温暖的问候: 阿卜杜拉·沙希德。

2 个答案:

答案 0 :(得分:1)

$services = Service::with(['user'])->whereHas('user', function($q) {
                 $q->where('zipcode', '20006');
            })->get();

答案 1 :(得分:0)

最后知道了

$services = Service::whereHas('user', function($q)use($zipcode) {
                $q->where('zipcode' , $zipcode);
            })->get();
相关问题