Symfony 6 - 获取某些字段
Symfony 6 - fetch certain fields
在我的 table 我有: 'id, message, user(from User::class, foreign key) etc...'
我如何 select 特定字段?我只想获取消息和用户名,我该怎么做?
我试过这个
public function getNameAndMessage()
{
return $this->createQueryBuilder('c')
->select('c.message, c.user.username')
->orderBy('c.id', 'ASC')
->setFirstResult(5)
->getQuery()
->getResult()
;
}
但是出现错误:[Semantical Error] line 0, col 25 near 'username FROM': Error: Class App\Entity\Comment has no field or association named user.username
有人可以帮助我
要访问用户实体的属性,您必须像这样将其加入您的查询:
public function getNameAndMessage(){
return $this->createQueryBuilder('c')
->select('c.message, u.username')
->leftJoin('c.user','u')
->orderBy('c.id', 'ASC')
->getQuery()
->getResult();
}
在我的 table 我有: 'id, message, user(from User::class, foreign key) etc...'
我如何 select 特定字段?我只想获取消息和用户名,我该怎么做?
我试过这个
public function getNameAndMessage()
{
return $this->createQueryBuilder('c')
->select('c.message, c.user.username')
->orderBy('c.id', 'ASC')
->setFirstResult(5)
->getQuery()
->getResult()
;
}
但是出现错误:[Semantical Error] line 0, col 25 near 'username FROM': Error: Class App\Entity\Comment has no field or association named user.username
有人可以帮助我
要访问用户实体的属性,您必须像这样将其加入您的查询:
public function getNameAndMessage(){
return $this->createQueryBuilder('c')
->select('c.message, u.username')
->leftJoin('c.user','u')
->orderBy('c.id', 'ASC')
->getQuery()
->getResult();
}