在Laravel中创建并返回具有关系的模型

Sim*_*leJ 3 php laravel eloquent

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

GET端点使用雄辩的with方法,包括评论与响应笔者的数据:

public function getComments(Note $note) {
    return $note->comments()->with(['author'])->get();
}
Run Code Online (Sandbox Code Playgroud)

如何在创建/返回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;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找这样的东西(但这不起作用):

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']);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*łek 8

你应该尝试使用:

$comment->load('author');
return $comment;
Run Code Online (Sandbox Code Playgroud)

加载author评论关系.