'datetime', 'used_at' => 'datetime', ]; /** * 關聯機台 */ public function machine(): BelongsTo { return $this->belongsTo(Machine::class); } /** * 關聯建立者 */ public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); } /** * 判斷是否可用 */ public function isValid(): bool { return $this->status === 'active' && $this->expires_at->isFuture(); } /** * 產生唯一的取貨碼 (4位) */ public static function generateUniqueCode(int $machineId): string { do { $code = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT); $exists = self::where('machine_id', $machineId) ->where('code', $code) ->where('status', 'active') ->where('expires_at', '>', now()) ->exists(); } while ($exists); return $code; } }