简体   繁体   English

Laravel集合映射功能会覆盖默认集合

[英]Laravel collection map function overrides default collection

I have a code where I use map to create a new collection of high scores. 我有一个代码,可以在其中使用地图来创建新的高分集合。 The problem I have is that it overrides the default user collections. 我的问题是它会覆盖默认的用户集合。 Which is not my intention. 这不是我的意图。

Here is the code 这是代码

    $users = Users::all();
    $highscore = $users->map(
        function ($user) {
            $calls = $user->calls->filter(
                function ($call) {
                    $date = Carbon::parse($call->datetime)->format("Y-m-d");
                    $today = Carbon::now()->format("Y-m-d");
                    return $date == $today;
                }
            );
            return [
                'id' => $user->id,
                'duration' => $calls->sum('duration'),
            ];
        }
    );

If i dump the first user after getting all the users I get the first user. 如果我在获得所有用户后转储第一个用户,我将获得第一个用户。 Like this. 像这样。

$users = Users::all();
dd($users->first());

If I dump the first user after the high score map. 如果我在高分地图之后转储第一个用户。 I get all Calls from that user which is another model. 我从该用户那里获得了所有呼叫,这是另一个模型。 Which means that the users collection has been modified. 这意味着用户集合已被修改。 Like this. 像这样。

$highscore = $users->map(
    function ($user) {
        $calls = $user->calls->filter(
            function ($call) {
                $date = Carbon::parse($call->datetime)->format("Y-m-d");
                $today = Carbon::now()->format("Y-m-d");
                return $date == $today;
            }
        );
        return [
            'id' => $user->id,
            'duration' => $calls->sum('duration'),
        ];
    }
);
dd($users->first()):

Any idea on how to handle this behaviour? 关于如何处理这种行为的任何想法吗?

The map function returns an array of [[$userId => $duration], ...]. map函数返回[[$ userId => $ duration],...]的数组。 What you want to do is to order your users by the sum of their calls. 您要做的是按用户的通话总数来对其排序。

I believe that, in order to do that easily, you should add to your User model: 我相信,为了轻松做到这一点,您应该添加到用户模型:

public function getTodayCallSum() {
    return $user->calls->filter(function($call) {
        $date = Carbon::parse($call->datetime)->format("Y-m-d");
        $today = Carbon::now()->format("Y-m-d");
        return $date == $today;
    })->sum('duration');
}

And then edit your query: 然后编辑您的查询:

$users = User::all();
$firstUser = $users->sortBy('todayCallSum')->first();

I haven't tested this code, but I think it should help you towards the right direction. 我尚未测试此代码,但我认为它应该可以帮助您朝正确的方向发展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM