cuentas === null) { $this->cuentas = $this->parentOf(Cuenta::class, [Model::CHILD_KEY => 'categoria_id']); if ($this->cuentas !== null) { usort($this->cuentas, function($a, $b) { return strcmp($a->nombre, $b->nombre); }); } } return $this->cuentas; } protected $tipo; public function tipo() { if ($this->tipo === null) { $this->tipo = $this->childOf(TipoCategoria::class, [Model::SELF_KEY => 'tipo_id']); } return $this->tipo; } public function getCuentasOf($tipo) { return $this->factory->find(Cuenta::class) ->select([['cuentas', '*']]) ->join([ ['tipos_cuenta', 'tipos_cuenta.id', 'cuentas.tipo_id'] ]) ->where([ ['tipos_cuenta.descripcion', $tipo], ['cuentas.categoria_id', $this->id] ]) ->many(); } protected $activos; public function activos() { if ($this->activos === null) { $this->activos = $this->getCuentasOf('Activo'); } return $this->activos(); } protected $pasivos; public function pasivos() { if ($this->pasivos === null) { $this->activos = $this->getCuentasOf('Pasivo'); } return $this->pasivos; } protected $ganancias; public function ganancias() { if ($this->ganancias === null) { $this->ganancias = $this->getCuentasOf('Ganancia'); } return $this->ganancias; } protected $perdidas; public function perdidas() { if ($this->perdidas === null) { $this->perdidas = $this->getCuentasOf('Perdida'); } return $this->perdidas; } protected $saldo; public function saldo(Service $service = null) { if ($this->saldo === null) { $this->saldo = 0; if ($this->cuentas() !== null) { $sum = 0; $debitos = ['Activo', 'Perdida']; foreach ($this->cuentas() as $cuenta) { if (array_search($cuenta->tipo()->descripcion, $debitos) !== false) { $sum -= $cuenta->saldo($service, true); continue; } $sum += $cuenta->saldo($service, true); } $this->saldo = $sum; } } return $this->saldo; } public function toArray(): array { $arr = parent::toArray(); $arr['tipo'] = $this->tipo()->toArray(); return $arr; } }