I have 2 linked entities: User and Acess. I want my doctrine User entity to have a field that informs me if the user has acesses or not. I can't do a simple OneToMany relationship between the two tables, because there is thousands of acesses and it would be too costly to get thousands of records from the database once I only need to know if there is any. What I would want is a field linked to a native query like:
select * from accesses where user = <whatever> limit 1
More specifically, something like:
/**
* USer
*
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User {
/**
* @ORM\Column(name="user_id", type="bigint", nullable=false)
* @ORM\Id
*/
private $id;
/**
* @ORM\Column(name="name", type="string", length=300, nullable=false)
* @Assert\NotBlank()
*/
private $name;
/**
* @ORM\Query="select exists (select id_acesses from accesses where user = "$id" limit 1)"
*/
private $hasAcesses;
}
Is this possible ? is there another way to do this ?
Edit:
based on @Otanaught answer below, I have done some tests:
Using a OneToMany relation with EXTRA_LAZY fetch:
user-getAccesses()->isEmpty() selected the whole collection
user-getAccesses()->count() used count(*) in the database which took 243ms to return
for comparasion my query above who did what I want took 12ms in average with peeks of 2ms or even 1ms.
Maybe the good folks at doctrine could implement this at isEmpty for extra lazy queries ?
Thanx @Otanaught