iiirxs
iiirxs

Reputation: 4582

Symfony: Filter ArrayCollection by associated entity id

I have a User entity and a Usecase entity. This 2 entities are associated by a ManyToMany association, but this association also holds another property, called "environment". To implement this relationship I also have an entity called UserUsecase that has a ManyToOne relationship with User, a ManyToOne relationship with Usecase and the extra field "environment". When fetching a user from the database, his usecases are being fetched as well, so the user has an ArrayCollection of objects of type UserUsecase that represent all the usecases a user has. What I want to do is to filter this ArrayCollection by usecase_id. The UserUsecase class has the structure below:

class UserUsecase
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="userUsecases")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

/**
 * @ORM\ManyToOne(targetEntity="Usecase", inversedBy="userUsecases")
 * @ORM\JoinColumn(name="usecase_id", referencedColumnName="id")
 */
protected $usecase; 

/**
 * @ORM\Column(type="integer")
 */
protected $environment;
}

So I tried this inside the User class:

public function filterUsecases($usecase_id){
    $criteria = Criteria::create();
    $criteria->where(Criteria::expr()->eq('usecase', $usecase_id));
    return $this->userUsecases->matching($criteria);
}

It makes sense to me that even the field usecase of the class UserUsecase is an object of type Usecase, it should resolve to its id and the equation would hold when the ids matched. Still this doesn't seem to work, and I cannot find how to implement this filtering. Isn't it possible to be done this way? I found a relevant article that seems to do exactly what I want but this is not working in my case. Here is the article! Am I doing something wrong?

Thanks in advance!

Upvotes: 2

Views: 686

Answers (1)

rafrsr
rafrsr

Reputation: 2030

Unless you have many many use cases per user(thousands) I recommend:

public function filterUsecases(Usecase $useCase){
    $criteria = Criteria::create();
    $criteria->where(Criteria::expr()->eq('usecase', $useCase));
    return $this->userUsecases->matching($criteria);
}

Then:

$user->filterUsecases($useCase);

Or passing reference

$user->filterUsecases($em->getReference(Usecase::class, $id));

Upvotes: 1

Related Questions