- Laravel Version: 5.4.23
- PHP Version: 7.1.3
- Database Driver & Version: MySQL 5.7.16 (community)
Description:
I'm trying to count all customer's contacts (CustomerContacts model) with phone number, but it fails because the model (Customer) loses relationship with company_id (Company model) if you use it with method withCount(..). See the example below.
Steps To Reproduce:
$customers = \App\Customer::where('company_id', '=', 4)->withCount(['contacts' => function($query) { $query->where('phone_no', '!=', ''); }])->select(\DB::raw('customers.*'))->paginate(5);
Query log:
select count() as aggregate from customers
where company_id
= '4';
select customers. from customers
where company_id
= '' limit 5 offset 0;