Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

Doctrine2 error al hacer getQuery

Estas en el tema de Doctrine2 error al hacer getQuery en el foro de Frameworks y PHP orientado a objetos en Foros del Web. Buenas Estoy armando esta consulta para poder listar usuarios de un grupo, tengo integrado doctrine2 a Zend y funcionando bien, el drama es con esta ...
  #1 (permalink)  
Antiguo 23/05/2011, 08:25
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Doctrine2 error al hacer getQuery

Buenas

Estoy armando esta consulta para poder listar usuarios de un grupo, tengo integrado doctrine2 a Zend y funcionando bien, el drama es con esta consulta:

Código PHP:
$qb $this->_em->createQueryBuilder();
        
$qb->select('u.id_usuario')
            ->
addSelect('u.nombre')
            ->
addSelect('u.apellido')
            ->
from('usuario u, ''mail_grupo m')
                        ->
where($qb->expr()->like('m.id_grupo'$qb->expr()->literal($id_grupo)))
                ->
orderBy('u.nombre');

              return 
$qb->getQuery()->getResult(); 
El error que obtengo es:

An error occurred
Application error
Exception information:

Message: [Semantical Error] line 0, col 47 near 'usuario u, mail_grupo': Error: Class 'usuario' is not defined.

Si hago solo return $qb; obtengo la consulta y al probarla en phpmyadmin me da bien los resultados, imagino esta bien armada ya que no obtengo errores y muestra lo que busco, pero a que se debe este error?
  #2 (permalink)  
Antiguo 23/05/2011, 08:33
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

La clase se llama usuario en minúscula ?, si la query esta bien, el problema es al hacer el hydrate.
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 23/05/2011, 08:36
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Respuesta: Doctrine2 error al hacer getQuery

Cita:
Iniciado por masterpuppet Ver Mensaje
La clase se llama usuario en minúscula ?, si la query esta bien, el problema es al hacer el hydrate.
No entiendo a que clase se refiere si estoy llamando a una tabla de la db con el from, y si esta en minuscula, usuarios, no es ninguna clase, es un select a la db.

el hydrate lo tengo asi:

Código PHP:
$qb->getQuery()->getResult(Query::HYDRATE_OBJECT); 
  #4 (permalink)  
Antiguo 23/05/2011, 08:40
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Es que ese es el problema, el DQL relaciona modelos no tablas, http://www.doctrine-project.org/docs...-language.html, presta especial atención a la primer nota en amarillo.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #5 (permalink)  
Antiguo 23/05/2011, 09:40
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Respuesta: Doctrine2 error al hacer getQuery

Y de que forma podria solucionarlo o como se usa?
  #6 (permalink)  
Antiguo 23/05/2011, 10:11
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Doctrine2 error al hacer getQuery

Pues tienes que crear los modelos de tus objetos para que puedas usar DQL para buscar sobre esos modelos, ya que de lo contrario solo necesitas hacer un SQL Query directo pero sin usar Doctrine.

Saludos.
  #7 (permalink)  
Antiguo 23/05/2011, 10:14
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Como se utiliza esta justamente en el link que te pase, que es exactamente lo que tienes echo ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #8 (permalink)  
Antiguo 23/05/2011, 10:17
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Respuesta: Doctrine2 error al hacer getQuery

Me podrias mostrar un ejemplo como hacerlo con mi consulta?, lo estoy haciendo dentro de los daos, son modelos no?

Tengo creado dentro de la carpeta dao (Data Access Objects) cada funcion donde hago las consultas, llamo a doctrine asi:

Código PHP:
use DoctrineORMAbstractQuery
    
DoctrineORMEntityManager,
    
DoctrineORMQuery,
    
DoctrineORMQueryExpr,
    
DoctrineORMQueryExprJoin,
    
DoctrineORMQueryResultSetMapping,
    
DoctrineORMQueryBuilder,
    
DoctrineORMEvents,
    
InmoDoctrineORMToolsDAOGenericDao
Y la clase
Código PHP:
class Usuario_Dao_UsuarioDao extends Usuario_Library_PerfilDao 
Donde tengo esta funcion:

Código PHP:
 public function findUsuarios($id) {
            
$qb $this->_em->createQueryBuilder();
        
$qb->select('u.id_usuario')
            ->
addSelect('u.nombre')
            ->
addSelect('u.apellido')
            ->
from('usuario u, ''mail_grupo m')
                        ->
where($qb->expr()->like('m.id_grupo'$id))
                ->
orderBy('u.nombre');
              return 
$qb->getQuery()->getResult(AbstractQuery::HYDRATE_OBJECT);

        } 
  #9 (permalink)  
Antiguo 23/05/2011, 10:21
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Habría que ver los modelos y en caso de que no uses annotations ver el yml o xml.
__________________
http://es.phptherightway.com/
thats us riders :)
  #10 (permalink)  
Antiguo 23/05/2011, 12:13
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Y que sistema de mapeo estas utilizando ? annotations, xml, yml ?, podrías postear algún Entity completo para ver que es lo que tienes ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #11 (permalink)  
Antiguo 23/05/2011, 12:20
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Respuesta: Doctrine2 error al hacer getQuery

Por ej:

Código PHP:
<?php
/**
 * Usuario Class
 * 
 * Represents a billing account in the system.
 * 
 * @author Lucas
 *
 * @Entity 
 */

class Usuario_model_usuario extends Usuario_Model_Usuario
{
    
    protected 
$usuario         null;

    
/**
     * @param string $rol
     * @param Usuario_Model_Usuario $usuario
     */
    
public function __construct($rolUsuario_Model_Usuario $usuario) {
        
parent::__construct($rol);
        
$this->usuario $usuario;
    }
    
    public function 
__toString() {
        return 
sprintf("%s (%s/%s)"$this->email$this->rol$this->usuario->getDatosUsuario());
    }
    

}
Ese es mi entity dentro de la carpeta models
  #12 (permalink)  
Antiguo 23/05/2011, 12:35
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Lo que me estas mostrando es una clase pero no es un Entity, debería ser algo así:

Código PHP:
Ver original
  1. namespace GOU\Entity;
  2.  
  3. /**
  4.  *
  5.  * @Entity
  6.  * @Table(name="ladders")
  7.  *
  8.  */
  9. class Ladder
  10. {
  11.     /**
  12.      * @Id @Column(type="integer") @GeneratedValue
  13.      * @var integer $id
  14.      */
  15.     private $id;
  16.    
  17.     /**
  18.      * @Column(length="50", unique="true", nullable="false")   
  19.      * @var string $name
  20.      */
  21.     private $name;
  22.    
  23.     /**
  24.      * @Column(type="text")  
  25.      * @var text $description
  26.      */
  27.     private $description;
  28.    
  29.     /**
  30.      * @Column(name="started_at", type="datetime") 
  31.      * @var DateTime $startAt
  32.      */
  33.     private $startAt;
  34.    
  35.     /**
  36.      * @ManyToMany(targetEntity="GOU\Entity\Clan", inversedBy="ladders")
  37.      * @var Doctrine\Common\Collections\ArrayCollection
  38.      */
  39.     private $teams;
  40.    
  41.     /**  
  42.      * Ladder constructor
  43.      */
  44.     public function __construct()
  45.     {
  46.         $this->teams = new Doctrine\Common\Collections\ArrayCollection();
  47.     }
  48.    
  49.     /**
  50.      * Get Id
  51.      * @return integer   
  52.      */
  53.     public function getId()
  54.     {
  55.         return $this->id;
  56.     }
  57.    
  58.     /**  
  59.      * Setter name
  60.      * @param string $name
  61.      */
  62.     public function setName($name)
  63.     {
  64.         $this->name = $name;
  65.     }
  66.    
  67.     /**
  68.      * Getter name
  69.      * @return string    
  70.      */
  71.     public function getName()
  72.     {
  73.         return $this->name;
  74.     }
  75.    
  76.     /**  
  77.      * Setter description
  78.      * @param text $desc
  79.      */
  80.     public function setDescription($desc)
  81.     {
  82.         $this->description = $desc;
  83.     }
  84.    
  85.     /**
  86.      * Getter description
  87.      * @return text  
  88.      */
  89.     public function getDescription()
  90.     {
  91.         return $this->description;
  92.     }
  93.        
  94.     /**  
  95.      * Setter startAt
  96.      * @param DateTime $startAt
  97.      */
  98.     public function setStartAt(DateTime $time)
  99.     {
  100.         $this->startAt = $time;
  101.     }
  102.    
  103.     /**
  104.      * Getter startAt
  105.      * @return Datetime  
  106.      */
  107.     public function getStartAt()
  108.     {
  109.         return $this->startAt;
  110.     }
  111.    
  112.    
  113.     /**
  114.      * Get ladders
  115.      * @return Doctrine\Common\Collections\ArrayCollection
  116.      */
  117.     public function getLadders()
  118.     {
  119.         return $this->modes;
  120.     }
  121.    
  122.     /**
  123.      * Add team
  124.      * @param \GOU\Entity\Clan $team
  125.      */
  126.     public function addTeam(\GOU\Entity\Clan $team)
  127.     {
  128.         $this->teams[] = $team;
  129.     }
  130.    
  131.     /**
  132.      * @return Doctrine\Common\Collections\ArrayCollection;
  133.      */
  134.     public function getTeams()
  135.     {
  136.         return $this->teams;
  137.     }
  138. }

Te sugiero que empieces por leer la documentación http://www.doctrine-project.org/docs...roduction.html.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #13 (permalink)  
Antiguo 23/05/2011, 12:39
 
Fecha de Ingreso: agosto-2003
Mensajes: 906
Antigüedad: 20 años, 8 meses
Puntos: 3
Respuesta: Doctrine2 error al hacer getQuery

Si lo tengo, llamado usuario.php y que tiene algo como

Código PHP:
use DoctrineCommonCollectionsArrayCollection,
    
InmoCommonIEquality,
    
InmoCommonEncriptador;
    
class 
Usuario implements IEquality
{

    protected 
$id                 null;

    protected 
$nombre             null;

    protected 
$email             null;

    private 
$password             null;

    protected 
$rol                 null;
    
    protected 
$ultimoLogin         null;

    protected 
$direccion         null;
    
/**
     * @var bool
     * 
     * @Column(name="activo", type="boolean", nullable=false)
     */
    
protected $activo             true;
    
/**
     * @var DateTime
     * 
     * @Column(name="creado", type="datetime", nullable=false)
     */
    
protected $creado             null;
    
/**
     * @var DateTime
     * 
     * @Column(name="actualizado", type="datetime", nullable=false)
     */
    
protected $actualizado         null;
    
    
/**
     * @return string
     */
    
public function __toString()
    {
        return 
sprintf("%s (%s)"$this->email$this->rol);
    }
    
    
    
/**
     * @param string $rol
     */
    
public function __construct($rol) {
        
$this->rol $rol;
    }

    
/**
     * @return integer
     */
    
public function getId() { return $this->id; }
    
    
/**
     * @return string
     */
    
public function getNombre() { return $this->nombre; }
    
/**
     * @param string $nombre
     */
    
public function setNombre($nombre) { $this->nombre $nombre; }

    
/**
     * @param string $email
     */
    
public function setEmail($email) { $this->email $email; }
    }

    public function 
getEmail() { return $this->email; }
    
/**
     * @return DateTime
     */
    
public function getUltimoLogin() { return $this->ultimoLogin; }
    
/**
     * @param DateTime $latestLogin
     */
    
public function setUltimoLogin(DateTime $ultimoLogin) { $this->ultimoLogin $ultimoLogin; }
    
    
/**
     * @return string
     */
    
public function getDireccion() { return $this->direccion; }
    
/**
     * @param string $direccion
     */
    
public function setDireccion($direccion) { $this->direccion $direccion; }

    
/**
     * @return bool
     */
    
public function isActivo() { return $this->activo; }
    
/**
     * @param bool $active
     */
    
public function setActivo($activo) { $this->activo $activo; }
    
    
/**
     * @return DateTime
     */
    
public function getCreado() { return $this->creado; }
    
/**
     * @return DateTime
     */
    
public function getActualizado() { return $this->actualizado; }
    
    
/** @PrePersist */
    
public function onPrePersist()
    {
        
$this->creado = new DateTime('now');
    }

    
/** @PreUpdate */
    
public function onPreUpdate()
    {
        
$this->actualizado = new DateTime('now');
    }

  #14 (permalink)  
Antiguo 23/05/2011, 12:55
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Doctrine2 error al hacer getQuery

Ahora si empezamos a hablar, a ver, tienes que agregar el @Entity, es obligatorio sino doctrine no lo reconoce como tal, y deberías configurar el resto de datos, el id no tiene @Id ni el strategy, tampoco tienes relaciones creadas, si un usuario tiene grupos deberia tener esa relación, a menos que esa unidireccional de grupos a usuario.
Luego que este todo configurado puede empezar con el DQL, y lo que debes relacionar es el modelo, no la tabla, ejemplo(tomado de la doc):

Código PHP:
Ver original
  1. $query = $em->createQuery('SELECT u FROM MyProject\Model\User u WHERE u.age > 20');
  2. $users = $query->getResult();

Otra cosa, si estas trabajando con Zend, porque los modelos no pertenecen a ningun Namespace, deberían ser algo así:
  1. Application_Entity_User
  2. Application_Model_User
  3. Application_Model_Entity_User
  4. Proyect_Entity_User

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)

Etiquetas: doctrine2, getquery
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:03.