db ->table($this->table . " t1") ->select( "t1.id, t1.pedido_id as pedido, t3.id as presupuesto,t1.cajas, t1.cajas as cajasRaw, t3.titulo as titulo, t1.unidades_envio as unidadesEnvio, t1.unidades_envio as unidadesEnvioRaw, t1.unidades_total as unidadesTotal, IFNULL(( SELECT SUM(t_sub.unidades_envio) FROM " . $this->table . " t_sub JOIN envios e ON e.id = t_sub.envio_id JOIN presupuesto_direcciones d ON d.presupuesto_id = t_sub.presupuesto_id WHERE e.finalizado = 1 AND t_sub.pedido_id = t1.pedido_id AND e.direccion = d.direccion COLLATE utf8mb3_general_ci ), 0) as unidadesEnviadas, IFNULL(( SELECT ROUND(SUM(peso) / 1000, 1) FROM presupuesto_linea WHERE presupuesto_id = t3.id ), 0) AS pesoUnidad" ); $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left"); $builder->where("t1.envio_id", $envio_id); return $builder; } public function getMaxCaja() { $builder = $this->db ->table($this->table . " t1"); $builder->selectMax('CAST(t1.cajas AS UNSIGNED)', 'max_caja'); $builder->where('t1.cajas IS NOT NULL'); $query = $builder->get(); $row = $query->getRow(); $maxCaja = is_numeric($row->max_caja) ? (int) $row->max_caja : 0; return $maxCaja + 1; } }