mysqllaravelpdoeloquenttable-relationships

Select all from first table and order by Count(id) from second table where second.value = 1


There are two table videos and reactions.

enter image description here

I want to sort videos by likes descending. reactions table is same for likes and dislikes. (I did not want to create two different tables for likes and dislikes). There is reaction column in the reactions table where reaction = 1 means likes, reaction = 2 means disslikes

The thing is that my code without where('reactions.reaction', 1) returns all videos sorted by total reactions (likes + disslikes) and I need to sort by only likes.

If add where('reactions.reaction', 1) then my query will returns only videos with likes instead of all the videos.

I want to get all videos from the table sorted by likes and not just liked videos. What should I do?

$videos = Video::select('videos.id', DB::raw('count(reactions.id) as total'))
->leftJoin('reactions', 'reactions.at_video', '=', 'videos.id')
// ->where('reactions.reaction', 1) // I need this for only reactions
->groupBy('videos.id')
->orderBy('total', 'DESC')
->get();

dd($videos);

Solution

  • Massive thanks to fake97 for the solution.

    I needed to change ->where('reactions.reaction', 1) To >where(function ($q){ $q->where('reactions.reaction', 1)->orWhereNull(''reactions.reaction');})

    See the code below

    $videos = Video::select('videos.id', DB::raw('count(reactions.id) as total'))
    ->leftJoin('reactions', 'reactions.at_video', '=', 'videos.id')
    ->where(function ($q){ 
      $q->where('reactions.reaction', 1)->orWhereNull('reactions.reaction');
    })
    ->groupBy('videos.id')
    ->orderBy('total', 'DESC')
    ->get();
          
    dd($videos);