php - Doctrine 将一个实体发送给 DQL 的 NEW 构造函数

标签 php symfony doctrine-orm doctrine dto

我在 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 感兴趣

我尝试了很多解决方案,我找到了一个

http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#new-operator-syntax

所以现在我的 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/

相关文章:

php - 如何让我的脚本不断检查变量?

php - 使用 swift 和 API 进行 POST

php - Symfony2 用户切换后缺少 ROLE_PREVIOUS_ADMIN

php - Symfony2 在每次更新时重新创建表

Symfony 获取登录用户的 ID

php - cURL 命令行登录 (bash)

php - 如何使用 imagemagick 创建水印

php - 原则 2 不坚持从拥有一方到多方的关系

php - 如何使用多个数据库模式管理 Doctrine 查询

symfony - 选中表单类型复选框以创建表单 SonataAdminBundle