php - Doctrine getting relational entites by status flag
I have 3 tables users
, groups
, group_users
(holds relation between group and user)
The table of group_users
includes the following columns
-- (is_active 0: not active, 1: active)
| id | user_id | group_id | is_active |
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 0
In entity of |Group
I have a relational column like the following that gets group users using the relation in group_users
table
/*
* @ORM\Entity()
* @ORM\Table(name="groups")
*/
class |Group{
...
/**
* @var Collection||GroupUser[]
* @ORM\OneToMany(targetEntity="App\|Group\Domain\Entity\|GroupUser")
*/
private $group_users;
In entity of |Group
I want to get group users but only ones that are active. In normal condition the relation above gets all related entities.
If I need to give an example, according to above records in group_users
table, when I call variable like $this->group_users
I want to see that only first record is listed
| id | user_id | group_id | is_active |
| 1 | 1 | 1 | 1
not this
|| id | user_id | group_id | is_active |
| 2 | 1 | 2 | 0 |
Do you have any idea what's the best way to handle this problem, thanks.
Note: I don't want to physically delete any record.
Answer
Solution:
You can define a new getter in Group
entity which will filter out the related group users as per your criteria
use Doctrine\Common\Collections\Criteria;
class Group{
//...
protected getActiveGroupUsers() {
$criteria = \Doctrine\Common\Collections\Criteria::create()
->where(\Doctrine\Common\Collections\Criteria::expr()->eq("is_active", 1));
return $this->group_users->matching($criteria);
}
}
And when you query a group you can get the related active group users as
$group = $em->getRepository("...\Group")->find($id);
$group->getActiveGroupUsers();
Source