categoria === null) { $this->categoria = $this->childOf(Categoria::class, [Model::SELF_KEY => 'categoria_id']); } return $this->categoria; } protected $cuenta; public function cuenta() { if ($this->cuenta === null) { $this->cuenta = $this->childOf(TipoCuenta::class, [Model::SELF_KEY => 'tipo_id']); } return $this->cuenta; } protected $cargos; public function cargos() { if ($this->cargos === null) { $this->cargos = $this->parentOf(Transaccion::class, [Model::CHILD_KEY => 'hasta_id']); } return $this->cargos; } protected $abonos; public function abonos() { if ($this->abonos === null) { $this->abonos = $this->parentOf(Transaccion::class, [Model::CHILD_KEY => 'desde_id']); } return $this->abonos; } protected $transacciones; public function transacciones($limit = null, $start = 0) { if ($this->transacciones === null) { $transacciones = Model::factory(Transaccion::class) ->join('cuentas', 'cuentas.id = transacciones.desde_id OR cuentas.id = transacciones.hasta_id') ->whereEqual('cuentas.id', $this->id) ->orderByAsc('transacciones.fecha'); if ($limit !== null) { $transacciones = $transacciones->limit($limit) ->offset($start); } $this->transacciones = $transacciones->findMany(); foreach ($this->transacciones as &$transaccion) { $transaccion->setFactory($this->factory); if ($transaccion->desde_id === $this->id) { $transaccion->valor = - $transaccion->valor; } } } return $this->transacciones; } protected $saldo; public function saldo() { if ($this->saldo === null) { $this->saldo = 0; if (count($this->transacciones()) > 0) { $this->saldo = array_reduce($this->transacciones(), function($sum, $item) { return $sum + $item->valor; }); } } return $this->saldo; } public function toArray(): array { $arr = parent::toArray(); $arr['categoria'] = $this->categoria()->toArray(); $arr['saldo'] = $this->saldo(); $arr['saldoFormateado'] = '$' . number_format($this->saldo(), 0, ',', '.'); return $arr; } }