Ad

Get Count In Mysql Query In Laravel

- 1 answer

I wants to select the count of votes got for each items.Following query works fine but there is a problem if there is no vote for an item then that item is not showing in result.I actually wants details of each items and votes.If there is no vote for an item it should be shown count zero. How can i achieve it?

DB::table('wonders')
        ->leftjoin('vote','votes.wonderId','=','wonders.id')
        ->select('wonders.id','wonders.title',DB::raw('count(votes.vote) as votes'))
        ->get();
Ad

Answer

Try this

DB::table('wonders')
            ->leftjoin('vote','votes.wonderId','=','wonders.id')
            ->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
            ->groupBy('wonders.id')
            ->get();
Ad
source: stackoverflow.com
Ad