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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?