javascript - 如何在 Laravel 中显示每月的产品销量

标签 javascript laravel

我在这部分感到困难。 所以我打算显示第一个月到当前期间的产品销售数据A。每个月都会显示销售数据。 然而,我发现这里很难显示销售数据。另外,出现的月份必须仅限于本月,因此接下来的月份不会首先出现。

这是我的代码

Controller :

public function index($id)
    {
        $thisYears = date('Y');
        $thisMonth = date('m');

        $produk = Product::findOrFail($id);
        $transaksi = Transaction::where('product_id', $produk->id)
                     ->where('created_at', 'LIKE','%'.$thisYears.'%')
                     // ->Where('status','!=','Menunggu')
                     ->get();
        $totalTrans = $transaksi->count();


        /*Date*/
        $months = array(1 => 'Januari '.$thisYears, 2 => 'Februari '.$thisYears, 3 => 'Maret '.$thisYears, 4 => 'April '.$thisYears, 5 => 'Mei '.$thisYears, 6 => 'Juni '.$thisYears, 7 => 'Juli '.$thisYears, 8 => 'Agustus '.$thisYears, 9 => 'September '.$thisYears, 10 => 'Oktober '.$thisYears, 11 => 'November '.$thisYears, 12 => 'Desember '.$thisYears);
        $transposed = array_slice($months, date('n'), 12, true) + array_slice($months, date('n'), true);
        $last8 = array_reverse(array_slice($transposed, -8, 12, true), true);
        return view('admin.product.insight.index', compact('transaksi','totalTrans','thisMonth','months','transposed','last8'));
    }

JS:

https://pastebin.com/cT8VMSy8

image display product data sales

最佳答案

就像 mare96 提到的那样,尝试使用 Carbon。代码被注释以解释正在做什么。

$data = [];

// Circle trough all 12 months
for ($month = 1; $month <= 12; $month++) {
    // Create a Carbon object from the current year and the current month (equals 2019-01-01 00:00:00)
    $date = Carbon::create(date('Y'), $month);

    // Make a copy of the start date and move to the end of the month (e.g. 2019-01-31 23:59:59)
    $date_end = $date->copy()->endOfMonth();

    $transaksi = Transaction::where('product_id', $produk->id)
        // the creation date must be between the start of the month and the end of the month
        ->where('created_at', '>=', $date)
        ->where('created_at', '<=', $date_end)
        // ->Where('status','!=','Menunggu')
        ->count();

    // Save the count of transactions for the current month in the output array
    $data[$month] = $transaksi;
}

这将为您提供一个看起来像这样的数组,具体取决于您的数据:

array(12) {
  [1]=>int(254)
  [2]=>int(564)
  [3]=>int(345)
  [4]=>int(675)
  [5]=>int(234)
  [6]=>int(123)
  [7]=>int(143)
  [8]=>int(676)
  [9]=>int(787)
  [10]=>int(567)
  [11]=>int(780)
  [12]=>int(898)
}

关于javascript - 如何在 Laravel 中显示每月的产品销量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56252529/

相关文章:

javascript - 如何启用 CORS?

javascript - 某个类的所有输入到json

php - Laravel 选择默认禁用选项

javascript - 用于识别具有给定类名的范围的正则表达式

javascript - android系统: Transformer Prime上的 "touchmove"事件

javascript - 使用 map 函数从包含数组的对象创建一个数组

php - 查询内容最多的前 5 个类别,每个类别返回 5 个内容,并使用 laravel 将 associaled 用户名与内容连接起来

php - laravel where 数组类型的方法

javascript - Laravel,将 php 变量传递给 JS 函数,显示为键而不是值

php - 方法 validateConfirm 不存在 (Laravel)