Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to query if array field contains a certain value in Doctrine2?

Starting out with Symfony2 + Doctrine.

I have a table with User objects (fos_user), for which my schema contains a roles column of an 'array' type.

Doctrine saves fields of this type by serializing them from php 'array' to 'longtext' (in mysql's case).

So let's say I have the following users saved into DB:

User1: array(ROLE_ADMIN, ROLE_CUSTOM1)
User2: array(ROLE_ADMIN, ROLE_CUSTOM2)
User3: array(ROLE_CUSTOM2)

Now in my controller I want to select all users with ROLE_ADMIN set. Is there a way to write a DQL query which would directly return me User1 and User2? Or do I need to fetch all users to have Doctrine to unserialize roles column and then for each of them do in_array('ROLE_ADMIN', $user->getRoles())?

I have searched the DQL part of the manual, but so far did not find anything similar to my needs...

UPD: Found a question about the same thing which contains a working query code

like image 258
dimsuz Avatar asked Oct 29 '12 16:10

dimsuz


1 Answers

You can simply use LIKE statement described in this manual (yes, even on serialized objects).

I'd suggest you to create an entity class for roles and join it with the user entity by ManyToMany association.

like image 124
Vadim Ashikhman Avatar answered Oct 19 '22 11:10

Vadim Ashikhman