Sort collection by label

In a previous post, I asked about getting totals that turned out to be sum()values ​​in Laravel. However, when the data is returned, it displays the sum without any other information that is usually displayed (for example: relationships, timestamps, etc.). Normally this would not be a problem if I just took the sum of everything as one number.

Below is a hard-coded example of visual recreation, and below is the data that creates it.

Line Morris.JS Chart

data: [{
                period: '2016-04',
                views: 2666,
            }, {
                period: '2016-05',
                views: 2778,
            }, {
                period: '2016-06',
                views: 4912,
            }, {
                period: '2016-07',
                views: 3767,
            }, {
                period: '2016-08',
                views: 6810,
            }, {
                period: '2016-09',
                views: 5670,
            }, {
                period: '2016-10',
                views: 4820,
            }, {
                period: '2016-11',
                views: 15073,
            }],

, , . , , , , , , , , created_at .

return Post::where('user_id', Auth::user()->id)->withCount(['visitors' => function($query)
        {
            $query->where('created_at', '<=', Carbon\Carbon::now())->where('created_at', '>=', Carbon\Carbon::yesterday());
        }])->get()->sum('visitors_count');
+4
4

. , , . :

public function displayPeriodOverPeriodGraphics()
    {
        return dd(Visitor::all()->where('posts.user_id', Auth::user()->id)->groupBy(function($query)
        {
            return Carbon\Carbon::parse($query->created_at)->format('d');
        })->map(function($total)
        {
            return $total->count();
        }));
    }
0

. , mySql, , , :

DATE() , yyyy-mm-dd, GROUP BY COUNT(visitors)

@user_id, @start_range, @end_range

, @end_range. @end_range = 2016-11-17', '2016-11-17 10:10:00' . , , , 2016-11-17 23:59:59

 SELECT DATE(created_at), count(visitors)
 FROM posts
 WHERE user_id = @user_id
   AND created_at BETWEEN @start_range
                      AND @end_range
 GROUP BY DATE(created_at)
+2

- ?

function postsPerPeriod()
{
    $posts = Post::orderBy('created_at')->get()->groupBy(function ($date) {
        return Carbon::parse($date->created_at)->format('m');
    });

    return $posts->map(function ($month) {
        return $month->sum('visitors');
    })->toArray();
}

, . , , Carbon.

0
source

The basic scheme exists as such

Users:
-id (A user owns many posts; Each post has many visitors)
... (etc.)

Posts:
-id (this is not the primary identifier)
-uuid (this is the value that matters)
-user_id (Foreign Key)
... (etc.)

Visitors:
-id
-visitor_id
-posts_uuid (Foreign Key)
-created_at
-updated_at

Thus, it should be the lines of visitors created in a certain period of time for any record belonging to the user.

0
source

Source: https://habr.com/ru/post/1661109/


All Articles