0
我嘗試用myisam表連接many_many從一個數據庫加入myisam表。爲什麼symfony爲連接執行額外的查詢
我有表文章,article_category,演員,article_actor(和許多更類似many2many關係)。
我在
條安裝:
class Article{ //.... /** * @ORM\ManyToMany(targetEntity="Category", inversedBy="articles") * @ORM\JoinTable(name="article_category") */ protected $categories; /** * @ORM\ManyToMany(targetEntity="Actor", inversedBy="articles") * @ORM\JoinTable(name="article_actor") */ protected $actors; /** * @ORM\ManyToMany(targetEntity="Cameraman", inversedBy="cameramen") * @ORM\JoinTable(name="article_cameraman") */ public function __construct() { $this->categories = new ArrayCollection(); $this->actors = new ArrayCollection(); }
類別:
類分類{
/** * @ORM\ManyToMany(targetEntity="Article", mappedBy="categories") **/ protected $articles; public function __construct() { $this->articles = new ArrayCollection(); }
演員:
類演員{
/** * @ORM\ManyToMany(targetEntity="Article", mappedBy="actors") **/ protected $articles; public function __construct() { $this->articles = new ArrayCollection(); }
在ArticleRepository我甲肝查詢與聯接:
類ArticleRepository延伸EntityRepository {
個公共職能findArticleWithJoins($ _ titleSlug){$q = $this->createQueryBuilder('a') ->where('a.titleSlug = :titleSlug') ->setParameter('titleSlug', $_titleSlug) ->leftJoin('a.categories', 'c') ->leftJoin('a.actors', 'ac') return $q->getQuery()->getSingleResult();
} }
在我的控制器我取與相關的文章加入:
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository('MyBundle:Article')->findArticleWithJoins('theSlug');
return $this->render('MyBundle:Default:index.html.twig',array('article' => $article));
,最後在模板一旦我遍歷連接,有3個查詢:
{% block body %}
{{article.title}}<br/>
{{article.categories.0.name}}<br/>
{% for actor in article.actors %}
<li>{{ actor.firstName }} {{ actor.lastName }}</li>
{% endfor %}
{% endblock %}
第QUER是:
SELECT
a0_.id AS id0,
a0_.title AS title15,
a0_.orig_title AS orig_title16,
a0_.title_slug AS title_slug17,
FROM
article a0_
LEFT JOIN article_category a2_ ON a0_.id = a2_.article_id
LEFT JOIN category c1_ ON c1_.id = a2_.category_id
LEFT JOIN article_actor a4_ ON a0_.id = a4_.article_id
LEFT JOIN actor a3_ ON a3_.id = a4_.actor_id
WHERE
a0_.title_slug = ?
第二個查詢:
SELECT
t0.id AS id1,
t0.name AS name2,
t0.slug AS slug3,
FROM
category t0
INNER JOIN article_category ON t0.id = article_category.category_id
WHERE
article_category.article_id = ?
而第三個查詢:
SELECT
t0.id AS id1,
t0.first_name AS first_name2,
t0.last_name AS last_name3,
t0.name_slug AS name_slug4,
FROM
actor t0
INNER JOIN article_actor ON t0.id = article_actor.actor_id
WHERE
article_actor.article_id = ?
我想避免多個查詢通過使用該連接findArticleWithJoins()函數。 但結果是相同的只是查詢文章,然後選擇關係。
我做錯了什麼?
Whow完蛋了我一直在尋找小時,非常感謝:)。 – rechengehirn