Izzy
Izzy

Reputation: 53

Symfony2: how can I load a user taking into account its mapping entity?

Although I'm using Symfony 2.1 with FOSUserBundle and everything works perfectly, I don't know how I can resolve a problem.

Basically, I would like to know if there is a way to find (load or get) a user from the database taking into account a relationship with another entity.

This is the situation:

I have made that users can also login into my site thru a social network (Google, Facebook, LinkedIn, etc). I besides ask them for an offline access, so I can access their social accounts any time.

As each user can have as many connections as they want (or maybe none cause they are optionals), I've decided not to save this information in the user table. I've created an abstract entity called "SocialConnection" which is extended by the real ones (Google, Facebook, ect). In this entity I store the user information that I get when the user logs in my site thru those networks (user_id, social_id, access_token, etc), so in my User class I have mapped a collection of the abstract "SocialEngine" that allows me to have all networks together.

In order to be able to add others networks like Twitter, Yahoo and so on in the future, I think it is the way it should be.

So, the problem now is that when the user logs into my site thru any of these social networks I need to load him from the database knowing his social id, but I don't know how to do it.

I've seen that the method $this->findUserBy of UserManager find a user regarding a property but I think this is not the case.

What should I do to find a nice solution?

Thanks in advance.

Best regards, Izzy.

Upvotes: 4

Views: 411

Answers (1)

AdrienBrault
AdrienBrault

Reputation: 7745

To achieve this, you need to get deeper into doctrine's api. The base repositories methods (find, findBy etc...) won't be enough.

You need to use doctrine's DQL. It looks like SQL but you query based on your mapping metadata and not based on the database schema directly.

If your User has a OneToMany $socialAccounts property to the SocialEngine. You will be able to do something like:

SELECT u
FROM Bundle:User AS u
JOIN u.socialAccounts AS sa
WHERE sa.id = 34

But you can only query on SocialEngine's properties, not on the subclasses one ... (ie: You can't query on a SocialFacebookEngine's facebookId).

You either have to put all the twitter/facebook/etc data in the base SocialEngine class, on in the User class. Or you could create an entity for each "Social Engine", and create a OneToOne relation relation between each of theses engines and the User.

Upvotes: 2

Related Questions