I have an entity Follow that handles a manyToMany relationship between User entity instances. Columns of related table looks like:
Follow(id, follower_id, followee_id)
When I execute the following query(In order to get the followers of a specific user):
$em= $this->entityManager;
$query = $em->createQuery(
'SELECT f
FROM MembersManagementBundle:Follow f
WHERE p.followee = :wee'
)->setParameter('wee', 1);
$n= $query->getResult();
It (normally) gives me a result like:
array (size=4)
0 =>
object(Members\Bundle\ManagementBundle\Entity\Follow)[347]
private 'follower' =>
object(Members\Bundle\ManagementBundle\Entity\User)[283]
protected 'id' => int 2
.........
private 'followee' =>
object(Members\Bundle\ManagementBundle\Entity\User)[283]
protected 'id' => int 1
.........
1 =>
..........
While I would like to have something like:
array (size=4)
0 => '2'
1 => '3'
.....
I tried SELECT f.follower_id
, SELECT f.follower.id
and they give me syntax errors.
It requires a more advanced knowledge of DQL and query builder than mine and whihc I am seeking from your usual guidance here. Thanks in advance.
Progress:
I managed to make the resulting array smaller:
array (size=4)
0 =>
array (size=1)
'id' => int 2
1 =>
array (size=1)
'id' => int 3
2 =>
array (size=1)
'id' => int 4
3 =>
array (size=1)
'id' => int 5
But not as mentionned in my original question. How to remove the arrays inside of the main array?
$query = $em->createQuery(
'SELECT u.id
FROM MembersManagementBundle:Follow p, MembersManagementBundle:User u
WHERE p.followed = :wee
AND u.id= p.follower'
)->setParameter('wee', 1);
You probably want the IDENTITY()
DQL function which is new in 2.4 and, unfortunately, is buried away in the documentation (check the last entry in that section).
So your DQL might look something like:
SELECT IDENTITY(f.follower) AS f1_id, IDENTITY(f.followee) AS f2_id FROM MembersManagementBundle:Follow f WHERE p.followee = :wee
The reason for this is because DQL and Doctrine, by design, are a level of abstraction above your SQL, so it hides away the identity mapping you have to do in SQL and relational databases in favour of objects. So whereas in SQL you would just select the IDs from the join table, here you have to tell Doctrine that you want the IDENTITY
of the objects.
Also, because this DQL isn't returning an entity and is a partial query (documentation) you'll need to do another post-processing step to get your array, something like:
$arr = array_map(function($row) { return $row['f1_id']; }, $query->getResult());
Hope this points you in the right direction!