I have very basic knowledge of SQL and don't how to modify my query so it returns the expected result.
My entities Activity
has a field members (a manyToMany relation). An activity can be done by several members.
I want to select all the activities a specific member does NOT take part into. I know the member's id (my variable $selfId
).
Here's what I'm doing in ActivityRepository:
public function getCollectiveActivities($selfId)
{
$qb = $this->createQueryBuilder('a');
$qb->join('a.members', 'm')
->where('m.id != :selfId')
->setParameter('selfId', $selfId);
return $qb
->getQuery()
->getResult();
}
My problem: when an activity "owns" two or more members, if one of them has $selfId as id, this activity ends up in my query results. But since one of the members of this activity has the id $selfId, it should not be returned. What am I doing wrong?
EDIT
I think I need to be more restrictive, I just don't know how. Let's say I have two activities:
activity1 which is owned by member1 and member2 activity2 which is owned by member3 and member4
$selfId = 3 (this means I don't want to fetch activities owned by member3)
From what I understand, the join clause might return lines like these:
activity1 | memberId: 1 (different from selfId = 3 so activity1 will be fetched) activity1 | memberId: 2 (different from selfId = 3 so activity1 will be fetched) activity2 | memberId: 3 (= selfId so activity2 shouldn't be fetched) activity2 | memberId: 4 (different from selfId = 3 so activity2 WILL be fetched. PROBLEM???)
EDIT 2
Others already faced the same problem and found this solution and this one, but they seem a bit hacky. Any clue on how to improve them would be welcome.