我在这部分感到困难。 所以我打算显示第一个月到当前期间的产品销售数据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:
最佳答案
就像 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/