Doctrine 向 DQL 的 NEW 构造函数发送一个实体

2022-01-16 00:00:00 php symfony doctrine doctrine-orm dto

我在 Symfony2 中有一个带有 Doctrine 的博客应用程序,由三个实体组成

I have a Blog application in Symfony2 with Doctrine, made of three entities

  • 发布
  • 评论
  • 用户

一个帖子可以有很多评论

one Post can have many Comments

此应用程序有一个 json API 调用/me/comments"

this application has an json API call "/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}
    },

]

普通的学说函数返回我所有的关系(用户,帖子)在 json,我不想要因为 Post 可以包含巨大的文本,所以我只对 Id 感兴趣

The normal doctrine function returns me all the relation (User, Post) in the json, which I don't want as Post can contains huge text, so i'm only interested in the Id

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

I've tried many solutions and I've found that one

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

所以现在我的 DQL 查询看起来像这样

so now my DQL query looks like that

<代码>SELECT NEW CommentDTO(c) FROM Comment as c WHERE c.author = :user

CommentDTO 的构造函数是这样的

the constructor of CommentDTO looks like that

__construct(Comment c) {
   $this->text = c.getText();
   $this->post = [ 'id' => c.getPost().getId() ];
}

当我执行它时,我得到了

when I execute it I got

{
   "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 有十几个字段,并且一个一个地发送它们看起来非常 hackish.

of course I could give the parameter one by one but Comment has a dozen of fields and sending them one by one seems highly hackish.

有没有办法直接发送对象?

Is there a way to send the object directly ?

推荐答案

正如@Cerad 在评论中提到的,根据文档,在 2017 年仍然有用:

As mentioned by @Cerad in the comments, there is no current way to achieve this, according to the documentation, which is still relevant in 2017:

请注意,您只能将标量表达式传递给构造函数.

Note that you can only pass scalar expressions to the constructor.

我在 问题跟踪器中找不到相关的功能请求,因此很可能在可预见的将来不会实施.

I could not find a related feature request in the issue tracker, so it will likely not be implemented in the foreseeable future.

相关文章