问题描述
我有这两个模型:
customers(id,firstname,lastname,phone)
addresses(id,province_id,address,customer_id)
与关系:
class Customer extends Model
{
public function addresses()
{
return $this->hasMany(Address::class);
}
}
public function customer()
{
return $this->belongsTo(Customer::class,'customer_id');
}
我正在尝试获得 customers with address in certain city
return new CustomerCollection(Customer::has('addresses')
->with(array('addresses' => function($q) use ($field)
{
$q->where('province_id','like',$field)->get();
}))->orderBy('id','DESC')->paginate(100));
结果几乎没问题,当我只需要给定省内地址的客户时,我获得了所有客户(坏)的集合,但地址数组只包含给定省内地址的数据。
怎么了?如何从结果中去除省内没有地址的客户?
解决方法
您是否尝试过此操作,如果您不打算在查询中提供 Province_id,那么它将逃避条件并为您提供所有客户的地址,如果您提供 province_id
,您将获得居住在的唯一客户provind_id
Customer::query()->when($province_id,function($query){
$query->whereHas('addresses',function($query) use($province_id){
$query->where('province_id',$province_id);
});
})
->with('addresses')
->get();
更新:
class Customer extends Model
{
public function scopeFilterByProvince($query,$provinceId = null)
{
return $query->when($province_id,$province_id);
});
// if you pass name of province use this
return $query->when($province,function($query) use($province){
$query->whereHas('province',function($q) use($province){
$q->where('name','like','%{$province}%');
});
});
}
}
然后是控制器或你的仓库
Customer::filterByProvince($request->get('province_id'))
->with('addresses')
->get();
,
Customer::with('addresses')->whereHas('addresses',function ($q) use ($field) {
return $q->where('province_id','%'.$field.'%');
})
您不需要在关系的嵌套查询中使用 get()
。您的问题中的 like
语法也不正确。尝试以上解决方案