belongsTo(User::class); } public function holdings() { return $this->hasMany(InvestmentHolding::class); } public function expenses() { return $this->hasMany(Expense::class); } public function unpaidAmount() { $billingDay = $this->billing_day ?? 1; $now = now(); // 如果今天還沒到結帳日,帳單週期是上個月結帳日到這個月結帳日 if ($now->day < $billingDay) { $start = $now->copy()->subMonth()->setDay($billingDay); $end = $now->copy()->setDay($billingDay)->subDay(); } else { $start = $now->copy()->setDay($billingDay); $end = $now->copy()->addMonth()->setDay($billingDay)->subDay(); } return $this->expenses() ->whereBetween('date', [$start->toDateString(), $end->toDateString()]) ->sum('amount'); } }