GET端点使用Eloquent的方法将响应的作者数据包含在响应中:
public function getComments(Note $note) {
return $note->comments()->with(['author'])->get();
}
如何在创建/返回Eloquent模型时包含作者数据?这是我目前的方法:
public function postComment(Note $note, Request $request) {
$user = $this->appUserRepo->getFromrequest($request);
$text = $request->text;
$comment = $note->comments()->create([
'app_user_id' => $user->id,
'text' => $text
]);
return $comment;
}
我正在寻找这样的东西(但这不起作用):
public function postComment(Note $note, Request $request) {
$user = $this->appUserRepo->getFromrequest($request);
$text = $request->text;
$comment = $note->comments()->create([
'app_user_id' => $user->id,
'text' => $text
]);
return $comment->with(['author']);
}
解决方法:
你应该尝试使用:
$comment->load('author');
return $comment;
加载作者关系以进行评论.