如何在 Laravel 中一次延迟加载所有集合的关系

How to lazy load relations for all collections at once in Laravel

我正在开发一个预测足球比赛比分的应用程序。在应用程序中,当用户预测比赛比分时,我会实时更新 UI。这是为了显示预测主队获胜、平局或客队获胜的人的百分比。为了提高性能,我缓存了一些查询的数据,但是每次用户更改预测时我都需要延迟加载一个关系。

这是我的部分代码。

public function getGroupsProperty()
{
    $groups = Cache::remember('groups', '3600', function () {
        return Group::whereId(1)->with('matches')->get();
    });

    foreach($groups as $group) {
        foreach($group->matches as $match) {
            // comment 1
            $predictions = $match->predictions->whereNotNull('team_a_score')->whereNotNull('team_b_score');
            foreach($predictions as $prediction) {
                // code to show prediction chart for the match
            }
        }
    }
}

从上面的代码可以看出,我急于为 group 加载 matches。稍后在 // comment 1 之后的行中,我正在加载每场比赛的预测。由于匹配项超过 50 个,因此对数据库的调用过多。

我想知道是否有一种方法可以一次延迟加载所有 matchespredictions 关系。这会将查询计数减少到 1。

这在 Laravel 中可行吗?

你可以这样做,如果你阅读文档,你可以with('matches.predictions') and that will Eager Load (not Lazy Load) 模型。

我已经按照下面的方式完成了,现在可以正常工作了。

public function getGroupsProperty()
{
    $groups = Cache::remember('groups', '3600', function () {
        return Group::whereId(1)->with('matches')->get();
    });

    foreach($groups as $group) {
        // lazy load predictions here...
        $group->matches->load('predictions');
        foreach($group->matches as $match) {  
            $predictions = $match->predictions->whereNotNull('team_a_score')->whereNotNull('team_b_score');
            foreach($predictions as $prediction) {
                // code to show prediction chart for the match
            }
        }
    }
}