我有两个模型:
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');
}
我正在尝试获得地址在某个城市的客户
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,那么它将转义该条件并获得所有具有该地址的customer;如果您提供province_id
,您将获得居住在Provind_ID
中的唯一customer
Customer::query()->when($province_id,function($query){
$query->whereHas('addresses', function($query) use($province_id){
$query->where('province_id', $province_id);
});
})
->with('addresses')
->get();