Symfony 6 - fetch certain fields

Viewed 29

In my table I have: 'id, message, user(from User::class, foreign key) etc...'
How can I select specific fields ? I would like fetch only message and username, how can I do ?
I tried this

public function getNameAndMessage()
    {
        return $this->createQueryBuilder('c')
            ->select('c.message, c.user.username')
            ->orderBy('c.id', 'ASC')
            ->setFirstResult(5)
            ->getQuery()
            ->getResult()
        ;
    }

But an error appear: [Semantical Error] line 0, col 25 near 'username FROM': Error: Class App\Entity\Comment has no field or association named user.username Someone can help me please

1 Answers

To access the properties of the User entity, you must join it to your query like this:

public function getNameAndMessage(){
    return $this->createQueryBuilder('c')
            ->select('c.message, u.username')
            ->leftJoin('c.user','u')
            ->orderBy('c.id', 'ASC')
            ->getQuery()
            ->getResult();
}
Related