我最近解決了一個查詢ManyToMany
關係連接表的問題,解決方案與此answer相同,並且想知道它是如何工作的。 可以說我有groups
和team
之間的簡單ManyToMany
關係,將有會自動在這裏內連接如何使用Doctrine和Symfony2在多對多關係上工作
組實體
/**
* Groups
*
* @ORM\Table(name="groups")
* @ORM\Entity(repositoryClass="AppBundle\Model\Repository\GroupsRepository")
*/
class Groups {
/**
* @ORM\ManyToMany(targetEntity="Team", inversedBy="group")
*/
protected $team;
public function __construct() {
$this->team = new ArrayCollection();
}
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="groupname", type="string", length=255)
*/
private $groupname;
//obligatory getters and setters :)
球隊實體
/**
* Team
*
* @ORM\Table(name="team")
* @ORM\Entity(repositoryClass="AppBundle\Model\Repository\TeamRepository")
*/
class Team {
/**
* @ORM\ManyToMany(targetEntity="Groups", mappedBy="team")
*/
protected $group;
public function __construct(){
$this->group = new ArrayCollection();
}
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="teamname", type="string", length=255)
*/
private $team;
//[setters and getters here]
創建爲了一個groups_team
表要獲得一個組中的所有團隊,我將不得不查詢groups_team
table.i將直接在mysql中查詢該表,但在symfony的我不得不這樣做
$groups = $em->getRepository("AppBundle\Model\Entity\Groups")->findBy(array('tournament' => $tournament->getId()));
//get all teams with group id in groups_team table
foreach ($groups as $group) {
$teamsingroup = $em->getRepository("AppBundle\Model\Entity\Team")->createQueryBuilder('o')
->innerJoin('o.group', 't')
->where('t.id = :group_id')
->setParameter('group_id', $group->getId())
->getQuery()->getResult();
echo "</b>".$group->getGroupname()."</b></br>";
foreach ($teamsingroup as $teamingroup) {
echo $teamingroup->getTeam()."</br>";
}
}
有人能向我解釋如何innerJoin
是工作,什麼是這背後的概念,也許幾個文件來了解這一點。用symfony和doctrine有沒有更好的方法。
謝謝你,這減少了我的代碼,它開始了我思考更精簡的代碼的方式。這100%回答了我的問題。 SO是一個很棒的平臺。 +1 –