Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 5644

Get parents from a table and count there childs in Laravel

How to select all the parents from a table and count how many child they have

Here is my code:

DB::table('wiki_page')
    ->where('wiki_page.parent_id', '=', null)
    ->get();

Table

 id  |   name  | parent_id
 -------------------------
 1   | Laravel |  null
 2   | PHP     |   1
 3   | Dingo   |   1
 4   | Lumen   |  null
 5   | Semver  |   4

Upvotes: 1

Views: 745

Answers (1)

Arjun
Arjun

Reputation: 1439

I think you have to do like :

DB::table('wiki_page')->selectRaw('wiki_page.*, COUNT(wp.id) AS child')
    ->join('wiki_page AS wp','wiki_page.id','=','wp.parent_id')
    ->where('wiki_page.parent_id', '=', null)
    ->groupBy('wiki_page.id')
    ->get();

Upvotes: 3

Related Questions