Home > Enterprise >  How to check if model has even number of relationed records?
How to check if model has even number of relationed records?

Time:11-25

I have User model with hasMany relationship and I need to write a query and get only those users which has even number of relationed records.

Is it possible to somehow use whereHas with %2 condition? Or how else to do it?

CodePudding user response:

you can use withCount alongside havingRaw to do this:

  $usersWithEvenRelatedModel= User::withCount('relatedModels as relatedCount')
  ->havingRaw('relatedCount %2 =1')->get();

CodePudding user response:

You can do this with some grouping/having and raw queries:

$userWithEvenRelations = User::whereHas('related', function ($q) {
   $q->groupBy('user_id')->havingRaw('MOD(COUNT(user_id), 2) = 0');
});
  • Related