Symfony AJAX 响应不是 return 整个数据?

Symfony AJAX response doesn't return whole data?

我有一个简单的逻辑,它获取所有评论,然后我获取每个评论的所有子评论,然后 return 这到 Javascript(通过 AJAX),但它不会 return 整个回复。

控制器:

$comments = $commentRepo->getPaginationPost(1, 0, $id);

foreach ($comments as &$comment) {
    $subcomments = $commentRepo->getSubComments($comment->getId());
    $comment->subComments = $subcomments;
}

$response = [
    'comments' => $comments,
    'id' => $id,
    'totalPages' => $totalPages
];

return new JsonResponse($response);

如果我dump($reponse); exit;,在return之前看起来像这样:

ArticleController.php on line 194:
array:3 [
  "comments" => array:1 [
    0 => & Comment {#7263
      -id: 168
      -content: "Лошо е"
      -person: User {#5420
        #id: 3
        -firstName: "testtt"
        -favouriteArticles: PersistentCollection {#5653
          -snapshot: []
          -owner: User {#5420}
          -association: array:19 [ …19]
          -em: EntityManager {#3456 …11}
          -backRefFieldName: null
          -typeClass: ClassMetadata {#5424 …}
          -isDirty: false
          #collection: ArrayCollection {#5688
            -elements: []
          }
          #initialized: true
        }
        #username: "test@test.com"
        #usernameCanonical: "test@test.com"
        #email: "test@test.com"
        #emailCanonical: "test@test.com"
        #enabled: true
        #salt: null
        #password: "y$.8Ky5Jj71PUsGD9E04nre./xClPVZ/Uiia40PTQjGmMAqOFpW2mwi"
        #plainPassword: null
        #lastLogin: DateTime {#5416
          +"date": "2019-01-07 09:39:06.000000"
          +"timezone_type": 3
          +"timezone": "UTC"
        }
        #confirmationToken: null
        #passwordRequestedAt: null
        #groups: null
        #roles: []
      }
      -dateAdded: DateTime {#7260
        +"date": "2019-01-09 11:02:35.000000"
        +"timezone_type": 3
        +"timezone": "UTC"
      }
      -replyTo: 0
      -postId: 8
      +"subComments": []
    }
  ]
  "id" => "8"
  "totalPages" => 2.0
]

但是在 JS 中,如果我 console.log 的 returned 数据是:

here

只有子评论,无法访问评论内容

问题是您的属性是 protectedprivate,如 #- 符号所示。

protectedprivate 属性不会出现在您的响应中,因此您需要使用 getter 方法手动设置值或使您的属性 public。

您无法在此处自动将对象转换为 JSON。 因此,您需要为 JSON 准备数据作为可以转换为 JSON 的简单数组。此外,在 foreach 中使用对数据库的请求是个坏主意。