我有一个简单的逻辑,它获取所有注释,然后获取每个注释的所有子注释,并将其返回给Javascript(通过AJAX),但不会返回整个响应。
控制器:
$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;
,在返回之前,它看起来像这样:
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: "$2y$13$.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
返回的数据是:
只有子注释存在,我无法访问注释内容。
答案 0 :(得分:1)
问题是您的属性为protected
和private
,用#
和-
符号表示。
protected
和private
属性不会出现在您的响应中,因此您需要使用getter方法手动设置值或将属性公开。
答案 1 :(得分:1)
您不能在此处将对象自动转换为JSON。 因此,您需要将JSON数据准备为可以转换为JSON的简单数组。而且,在foreach内部使用对数据库的请求也是一个坏主意。