@KifayatMsd Check this package https://github.com/jarektkaczyk/eloquence - it provides Subquery helper class for such cases. Then you need something like this:
// assuming you have an eloquent model Ticket, for presentation
$countTickets = new \Sofa\Eloquence\Subquery(
Ticket::from('dental_support_tickets as t')
->selectRaw('count(t.id)')->whereRaw('t.category_id=c.id')->where('t.status', '0'),
'num_tickets' // alias
);
// now let's use query builder
$countAdmins = new \Sofa\Eloquence\Subquery(
DB::table('dental_support_category_admin as a')
->selectRaw('count(a.id)')->whereRaw('a.category_id=c.id'),
'num_admins' // alias
);
// finally eloquent result
Category::from('dental_support_categories as c')
->select('c.*', $countTickets, $countAdmins)
->addBinding($countTickets->getBindings(), 'select')
->where('c.status', 0)
->orderBy('c.title', 'asc')
->paginate()
It will automatically build the query for you:
select
c.*,
(select count (t.id) from dental_support_tickets t where t.category_id=c.id and t.status = ?) as num_tickets,
(select count(a.id) from dental_support_category_admin a where a.category_id=c.id) as num_admins
from dental_support_categories c
where c.status = ?
order by c.title ASC