Foros del Web » Programando para Internet » PHP » Symfony »

[SOLUCIONADO] Buscar por relacion manytomany

Estas en el tema de Buscar por relacion manytomany en el foro de Symfony en Foros del Web. Hola, tengo dos entidades, una con solo el id y un nombre (categoria) y otra que entre las propiedades una es un manytomany a la ...
  #1 (permalink)  
Antiguo 28/04/2013, 08:01
Avatar de jhg
jhg
 
Fecha de Ingreso: marzo-2012
Mensajes: 96
Antigüedad: 12 años, 1 mes
Puntos: 1
Buscar por relacion manytomany

Hola, tengo dos entidades, una con solo el id y un nombre (categoria) y otra que entre las propiedades una es un manytomany a la entidad anterior, y necesito en esta buscar las que coincidan con un id de la entidad anterior. ¿Es posible buscar segun el id de una entidad con la que se tiene un manytomany?

He buscado en Google pero me aparece como crear la relación many to many, pero eso ya lo tengo:
Código:
<?php
 
namespace Compartida\CompartidaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
 
/**
 * @ORM\Entity
 * @ORM\Table(name="adcategory")
 */
class Adcategory
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $show;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Adcategory
     */
    public function setName($name)
    {
        $this->name = $name;
    
        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set show
     *
     * @param boolean $show
     * @return Adcategory
     */
    public function setShow($show)
    {
        $this->show = $show;
    
        return $this;
    }

    /**
     * Get show
     *
     * @return boolean 
     */
    public function getShow()
    {
        return $this->show;
    }
}
Código:
<?php

namespace Compartida\CompartidaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="adsite")
 * @ORM\HasLifecycleCallbacks()
 */
class Adsite
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Adcategory")
     * @ORM\JoinTable(name="ad_category",
     *     joinColumns={@ORM\JoinColumn(name="ad_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
     * )
     */
    protected $category;

    /**
     * @ORM\ManyToOne(targetEntity="Username")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $username;

    /**
     * @ORM\Column(type="string")
     */
    protected $name;

    /**
     * @ORM\Column(type="string")
     */
    protected $lastname;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

    /**
     * @ORM\ManyToOne(targetEntity="Adsitetype")
     * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
     */
    protected $type;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $price;

    /**
     * @ORM\Column(type="string")
     */
    protected $email;

    /**
     * @ORM\Column(type="string")
     */
    protected $telephone;

    /**
     * @ORM\Column(type="string")
     */
    protected $city;

//    protected $images;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $approved;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;


    public function getDescription($length = null)
    {
        if (false === is_null($length) && $length > 0)
            return substr($this->description, 0, $length);
        else
            return $this->description;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->category = new \Doctrine\Common\Collections\ArrayCollection();
    }
    
    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Adsite
     */
    public function setName($name)
    {
        $this->name = $name;
    
        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set lastname
     *
     * @param string $lastname
     * @return Adsite
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;
    
        return $this;
    }

    /**
     * Get lastname
     *
     * @return string 
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Adsite
     */
    public function setTitle($title)
    {
        $this->title = $title;
    
        return $this;
    }

    /**
     * Get title
     *
     * @return string 
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Adsite
     */
    public function setDescription($description)
    {
        $this->description = $description;
    
        return $this;
    }

    /**
     * Set price
     *
     * @param float $price
     * @return Adsite
     */
    public function setPrice($price)
    {
        $this->price = $price;
    
        return $this;
    }

    /**
     * Get price
     *
     * @return float 
     */
    public function getPrice()
    {
        return $this->price;
    }

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

    /**
     * Get email
     *
     * @return string 
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set telephone
     *
     * @param string $telephone
     * @return Adsite
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
    
        return $this;
    }

    /**
     * Get telephone
     *
     * @return string 
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return Adsite
     */
    public function setCity($city)
    {
        $this->city = $city;
    
        return $this;
    }

    /**
     * Get city
     *
     * @return string 
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set approved
     *
     * @param boolean $approved
     * @return Adsite
     */
    public function setApproved($approved)
    {
        $this->approved = $approved;
    
        return $this;
    }

    /**
     * Get approved
     *
     * @return boolean 
     */
    public function getApproved()
    {
        return $this->approved;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Adsite
     */
    public function setCreated($created)
    {
        $this->created = $created;
    
        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime 
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Adsite
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;
    
        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime 
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Add category
     *
     * @param \Compartida\CompartidaBundle\Entity\Adcategory $category
     * @return Adsite
     */
    public function addCategory(\Compartida\CompartidaBundle\Entity\Adcategory $category)
    {
        $this->category[] = $category;
    
        return $this;
    }

    /**
     * Remove category
     *
     * @param \Compartida\CompartidaBundle\Entity\Adcategory $category
     */
    public function removeCategory(\Compartida\CompartidaBundle\Entity\Adcategory $category)
    {
        $this->category->removeElement($category);
    }

    /**
     * Get category
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Set username
     *
     * @param \Compartida\CompartidaBundle\Entity\Username $username
     * @return Adsite
     */
    public function setUsername(\Compartida\CompartidaBundle\Entity\Username $username = null)
    {
        $this->username = $username;
    
        return $this;
    }

    /**
     * Get username
     *
     * @return \Compartida\CompartidaBundle\Entity\Username 
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set type
     *
     * @param \Compartida\CompartidaBundle\Entity\Adsitetype $type
     * @return Adsite
     */
    public function setType(\Compartida\CompartidaBundle\Entity\Adsitetype $type = null)
    {
        $this->type = $type;
    
        return $this;
    }

    /**
     * Get type
     *
     * @return \Compartida\CompartidaBundle\Entity\Adsitetype 
     */
    public function getType()
    {
        return $this->type;
    }
}
__________________
JHG
  #2 (permalink)  
Antiguo 28/04/2013, 08:34
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: Buscar por relacion manytomany

No es un tema de Symfony sino de Doctrine, no entiendo muy bien cual quieres filtrar exactamente, que quieres obtener ?, todos los adsite que pertenezcan a determinada adcategory ?, en cualquier caso comprueba Expr\Join::WITH tanto en DQL como en el QueryBuilder a ver si es lo que necesitas.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 28/04/2013, 09:46
Avatar de jhg
jhg
 
Fecha de Ingreso: marzo-2012
Mensajes: 96
Antigüedad: 12 años, 1 mes
Puntos: 1
Respuesta: Buscar por relacion manytomany

Si, justo eso, obtener todos los adsite de un adcategory. Gracias porr los enlaces, auqnue no termino de entender del todo como hacerlo.

He hecho un intento, que almenos no da error, a ver si esto es lo que hacia falta:
Código:
    $sites = $em->createQueryBuilder()
                ->select('s')
                ->from('CompartidaCompartidaBundle:Adsite',  's')
                ->join('s.category', 'category')
                ->where("category.id = $id")
                ->addOrderBy('s.created', 'DESC')
                ->getQuery()
                ->getResult();
En la plantilla me aparece comoq ue no hay anuncios en esa categoria, hasta ahi bien porque no da error y aun no hay datos en la base de datos proque estoy aun con el formulario para añadirlos. ¿De momento llevo algun fallo en eso?
__________________
JHG

Última edición por jhg; 28/04/2013 a las 10:53 Razón: Agregar información

Etiquetas: relacion
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 01:00.