I have these two entities:
Message entity
class Message { /** * @ManyToOne(targetEntity="User") * @JoinColumn(name="author", referencedColumnName="id_user") */ protected $author;
User entity
class User { /** * @Id * @Column(type="integer", nullable=false, name="id_user") * @GeneratedValue(strategy="AUTO") */ protected $id; /** * @Column(type="string", nullable=false) */ protected $name;
I need to get the total of messages of user and its data in order to echo something like this:
echo $user->getName() . " have {$user->totalOfMessage()}";
I now that I can make a relation in User entity to get a message collection. But I don’t know if it necessary only to get the size.
Advertisement
Answer
Well, I found the answer. At least one good option.
As of Doctrine 2.1 you can mark associations as extra lazy. This means that calling $user->getMessages()->count() won’t load the messages, it will just issue a COUNT query to the database.
You can read about extra lazy collections here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/tutorials/extra-lazy-associations.html