Laravel雄辩的渴望加载多态性关系

发布于 2025-01-25 08:09:00 字数 506 浏览 4 评论 0原文

我使用Rappasoft/laravel-authentication-log与我的用户模型。它暴露了以下多态关系与用户模型:

public function authentications()
{
    return $this->morphMany(AuthenticationLog::class, 'authenticatable')->latest('login_at');
}

现在,如果我运行$ user-> authentications-> some_property$ useruser:用户: :get()集合),发出n+1个查询。我如何渴望加载这种关系?

我已经尝试了用户:: with('authentications') - > get(),但似乎无法正常工作。我仍然得到n+1个查询。

I am using rappasoft/laravel-authentication-log with my User model. It exposes the following polymorphic relation to the User model:

public function authentications()
{
    return $this->morphMany(AuthenticationLog::class, 'authenticatable')->latest('login_at');
}

Now, if I run $user->authentications->some_property ($user is from User::get() collection), it emits N+1 queries. How do I eager load this relationship?

I've tried User::with('authentications')->get() but it doesn't seem to be working. I'm still getting N+1 queries.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所谓喜欢 2025-02-01 08:09:00

好的,看来急切的负载正在正常工作。我正在使用$ user-> getlastLoginat()方法,该方法明确加载了关系:

    public function lastLoginAt()
{
    return optional($this->authentications()->first())->login_at;
}

我已经将代码更改为optional($ this-&this-> authertications-> first> first() ) - > login_at,我不再generatig n+1查询

Ok, It seems the eager loading is working as-is. I was using the $user->getLastLoginAt() method which loads the relationship explicitly:

    public function lastLoginAt()
{
    return optional($this->authentications()->first())->login_at;
}

I've changed the code to optional($this->authentications->first())->login_at and I'm no longer generatig N+1 queries

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文