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

前端之家收集整理的这篇文章主要介绍了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,'text' => $text
    ]);
    return $comment->with(['author']);
}

解决方法

你应该尝试使用:

$comment->load('author');
return $comment;

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

猜你在找的Laravel相关文章