如何为单个雄辩的对象急切加载关系?

Posted

技术标签:

【中文标题】如何为单个雄辩的对象急切加载关系?【英文标题】: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 时,我还想要嵌套用户对象,我该怎么做?

【问题讨论】:

【参考方案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

以上是关于如何为单个雄辩的对象急切加载关系?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 has_many 关系中急切加载最新的对象?

急切加载与加入获取相同吗?

如果急切加载的值具有价值,则仅返回雄辩的结果?

如何从 hasManyThrough 雄辩关系返回 Laravel 中的单个模型

在laravel [实现过滤器]中将多个表与雄辩和急切的加载一起加入

WCF 数据服务和 EF4 CTP5,如何为查询配置默认的急切加载模式?