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;

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...