Skip to content

Instantly share code, notes, and snippets.

@TheoKouzelis
Last active June 20, 2016 16:21
Show Gist options
  • Save TheoKouzelis/760950040dbc0073f36c2664a88fac05 to your computer and use it in GitHub Desktop.
Save TheoKouzelis/760950040dbc0073f36c2664a88fac05 to your computer and use it in GitHub Desktop.
This is a Laravel Eloquent scope query which will return all models that have relationship with all of the IDs supplied
<?php
namespace App;
trait QueryRelationships
{
public function scopeWhereHasRelationIds($query, $relationName, array $relationIdList)
{
$query->whereHas($relationName, function ($query) use ($relationIdList) {
$query->whereIn('id', $relationIdList)
->havingRaw('COUNT(id) = ?', [count($relationIdList)]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment