Doctrine 将一个实体发送给 DQL 的 NEW 构造函数
Doctrine send an entity to DQL's NEW constructor
我在 Symfony2 中有一个带有 Doctrine 的博客应用程序,由三个实体组成
- Post
- 评论
用户
一个Post可以有很多评论
- 一个用户可以有很多评论
此应用程序有一个 json API 调用“/me/comments”
我想要 return
[
{
'text': 'great post',
... 10 other field a comment can have ...
'post': { 'id': 3}
},
{
'text': 'i dont like it',
... 10 other field a comment can have ...
'post': {'id': 4}
},
]
正常的学说函数 return 是 json 中的所有关系(用户,Post),我不想要,因为 Post 可以包含巨大的文本,所以我只对 Id
感兴趣
我尝试了很多解决方案,我发现了一个
所以现在我的 DQL 查询看起来像这样
SELECT NEW CommentDTO(c) FROM Comment as c WHERE c.author = :user
CommentDTO 的构造函数看起来像这样
__construct(Comment c) {
$this->text = c.getText();
$this->post = [ 'id' => c.getPost().getId() ];
}
当我执行它时,我得到了
{
"code":500,
"message":"Argument 1 passed to MVMS\ApiBundle\Entity\CommentDTO::__construct() must be an instance of MVMS\ApiBundle\En
tity\Comment, integer given"
}
当然,我可以一个一个地给出参数,但是 Comment 有十几个字段,一个一个地发送它们似乎很老套。
有没有办法直接发送对象?
正如@Cerad 在评论中提到的,根据 documentation,目前没有实现此目的的方法,这在 2017 年仍然适用:
Note that you can only pass scalar expressions to the constructor.
我在 issue tracker 中找不到相关的功能请求,因此在可预见的将来很可能不会实现。
我在 Symfony2 中有一个带有 Doctrine 的博客应用程序,由三个实体组成
- Post
- 评论
用户
一个Post可以有很多评论
- 一个用户可以有很多评论
此应用程序有一个 json API 调用“/me/comments”
我想要 return
[
{
'text': 'great post',
... 10 other field a comment can have ...
'post': { 'id': 3}
},
{
'text': 'i dont like it',
... 10 other field a comment can have ...
'post': {'id': 4}
},
]
正常的学说函数 return 是 json 中的所有关系(用户,Post),我不想要,因为 Post 可以包含巨大的文本,所以我只对 Id
感兴趣我尝试了很多解决方案,我发现了一个
所以现在我的 DQL 查询看起来像这样
SELECT NEW CommentDTO(c) FROM Comment as c WHERE c.author = :user
CommentDTO 的构造函数看起来像这样
__construct(Comment c) {
$this->text = c.getText();
$this->post = [ 'id' => c.getPost().getId() ];
}
当我执行它时,我得到了
{
"code":500,
"message":"Argument 1 passed to MVMS\ApiBundle\Entity\CommentDTO::__construct() must be an instance of MVMS\ApiBundle\En
tity\Comment, integer given"
}
当然,我可以一个一个地给出参数,但是 Comment 有十几个字段,一个一个地发送它们似乎很老套。
有没有办法直接发送对象?
正如@Cerad 在评论中提到的,根据 documentation,目前没有实现此目的的方法,这在 2017 年仍然适用:
Note that you can only pass scalar expressions to the constructor.
我在 issue tracker 中找不到相关的功能请求,因此在可预见的将来很可能不会实现。