【问题标题】:How to eager load relations for single eloquent object?如何为单个雄辩的对象急切加载关系?
【发布时间】:2015-09-17 05:07:28
【问题描述】:

我有这个 Comment 模型与属于关系。

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

在我的控制器中:

public function store(Request $request)
{
    $comment = $this->dispatch(
        new StoreCommentCommand($request->body, Auth::user()->id, $request->post_id)
    );

    return $comment;
}

当我返回 $comment 时,我还想要嵌套用户对象,我该怎么做?

【问题讨论】:

    标签: json rest laravel eloquent


    【解决方案1】:

    如果有人偶然发现这一点,您可以在返回之前将用户分配给评论。

    $comment->user = Auth::user()
    return $comment
    

    这里不需要with eager-loading 函数。

    【讨论】:

      【解决方案2】:

      您需要在 Builder 对象上使用 with(),而目前您在 eloquent 对象上使用。这将是您的工作代码。

          return Comment::with('user')->where('id', $comment->id)->first();
      

      【讨论】:

      • 非常感谢!
      【解决方案3】:

      只是急于加载它...

      return $comment->with('user');
      

      【讨论】:

      • 首先应该是return $comment->with('user')->get();。其次我试过了,它返回数据库中的所有 cmets 和用户对象,我只需要一个:(
      • 您是否验证了从StoreCommentCommand 类返回的$commentCommentwith() 应该只将用户附加到您已有的 cmets。
      • 这是一个雄辩的对象。我做了$comment->save() 然后return $comment
      猜你喜欢
      • 2019-09-14
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      相关资源
      最近更新 更多