我有几个端点用于获取/发布对该应用程序中笔记的评论。
GET
端点使用 Eloquent 的 with
方法将评论的作者数据包含在响应中:
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;
为评论加载作者
关系。
关于php - 在 Laravel 中创建和返回具有关系的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100743/