gpt4 book ai didi

php - 在 Laravel 中创建和返回具有关系的模型

转载 作者:可可西里 更新时间:2023-11-01 00:18:49 25 4
gpt4 key购买 nike

我有几个端点用于获取/发布对该应用程序中笔记的评论。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com