dongmeiyi2266 2015-03-12 08:08
浏览 126
已采纳

Doctrine将实体发送给DQL的NEW构造函数

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

  • Post
  • Comment
  • User

  • one Post can have many Comments

  • one User can have many comments

this application has an json API call "/me/comments"

I would like it to 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}
    },

]

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

so now my DQL query looks like that

SELECT NEW CommentDTO(c) FROM Comment as c WHERE c.author = :user

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"

}

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 ?

  • 写回答

1条回答 默认 最新

  • dongyou7739 2017-06-29 17:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?