我在 Symfony2 中有一个包含 Doctrine 的博客应用程序,由三个实体组成
- 发布
- 评论
用户
一个帖子可以有很多评论
- 一个用户可以有很多评论
此应用程序有一个 json API 调用“/me/comments”
我希望它回来
[
{
'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}
},
]
正常的 doctrine 函数返回 json 中的所有关系(User,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 中找不到相关的功能请求, 因此在可预见的将来很可能不会实现。
关于php - Doctrine 将一个实体发送给 DQL 的 NEW 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004687/