微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在Laravel中创建并返回一个具有关系的模型

我有几个端点可以在此应用程序中获取/发布注释.

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;

加载作者关系以进行评论.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐