Skip to content

Instantly share code, notes, and snippets.

@Infernosquad
Created May 18, 2016 02:32
Show Gist options
  • Save Infernosquad/cc6237e7c782892e70ba33dd36976234 to your computer and use it in GitHub Desktop.
Save Infernosquad/cc6237e7c782892e70ba33dd36976234 to your computer and use it in GitHub Desktop.
Many to Many Query
<?php
namespace ContentBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Post
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $title;
/**
* @ORM\ManyToMany(targetEntity="Tag",inversedBy="tags",cascade={"persist", "remove"})
* @ORM\JoinTable(name="post_tags")
*/
protected $tags;
public function __construct() {
$this->tags = new ArrayCollection();
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
public function addTag(Tag $tag)
{
$tag->addPost($this);
$this->tags[] = $tag;
}
public function getTags()
{
return $this->tags;
}
}
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$qb = $this->getDoctrine()->getManager()->createQueryBuilder()
->select('t AS tag')
->addSelect('COUNT(p) AS num_posts')
->from('ContentBundle:Tag', 't')
->leftJoin('ContentBundle:Post', 'p', 'WITH', 't MEMBER OF p.tags')
->groupBy('t.id');
dump($qb->getQuery()->getResult());
}
}
array:2 [▼
0 => array:2 [▼
"tag" => Tag {#400 ▶}
"num_posts" => "2"
]
1 => array:2 [▼
"tag" => Tag {#406 ▶}
"num_posts" => "1"
]
]
<?php
namespace ContentBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Tag
*
* @ORM\Table()
* @ORM\Entity
*/
class Tag
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity="Post", mappedBy="tags")
*/
private $posts;
public function __construct($name = null)
{
$this->posts = new ArrayCollection();
$this->setName($name);
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Tag
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
public function addPost(Post $post)
{
$this->posts[] = $post;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment