Cakephp 3 filter by a many to many associated relation

37 Views Asked by At

I have a users table, roles and users_roles as a join / pivot table. I am tryin to create a query to retrive all the users that HAVE NOT these roles: interventor, editor, chief

At the moment this is my query but I am not getting the desiered results, because users with these roles still coming.

  $users = TableRegistry::getTableLocator()->get('Users');
            $allUsers = $users->find('all', ['order' => ['Users.id ASC']])->select([
                'id',
                'name',
                'surname',

            ])
                 
            ->contain('Roles', function (Query $q) {
                return $q
                    ->select(['slug'])
                    ->notMatching('Users.Roles', function ($q) {
                        return $q->where(['Roles.slug NOT IN' => ['interventor', 'editor', 'chief']]);
                    });      
            });

Thank you

1

There are 1 best solutions below

0
R0bertinski On

Ok I found asolution.

Just adding an innerJoin to the query.

->innerJoinWith('Roles')->where(['Roles.slug NOT IN' => ['interventor', 'editor', 'chief']]);