簡體   English   中英

Symfony2 映射 4 表內連接查詢到 Doctrine QueryBuilder

[英]Symfony2 Mapping 4 table Inner Join query to Doctrine QueryBuilder

我有 4 個表,實體中的屬性都相應地映射。 我正在嘗試根據選定的標簽查詢文章。

articles => id, title, author_id - NAMESPACE AppBundle/Enity/Article
tags => id, name - NAMESPACE AppBundle/Entity/Tag
article_tags => article_id, tag_id
authors=> id, name - NAMESPACE AppBundle/Entity/Author

我已經想出了如何獲取所有文章,其中標簽在 article_tags 表中具有與它們相關的 id,並按作者 id 進行過濾。 在 SQL 中,我的查詢如下所示。 測試和工作。

SELECT 
    articles.title, articles.id, authors.name
FROM
    article_tags
INNER JOIN tags
    ON article_tags.tag_id = tags.id
INNER JOIN articles 
    ON article_tags.article_id = article.id
INNER JOIN authors
    ON authors.id = articles.author_id
WHERE
    tags.id IN (1,2)

我正在嘗試構建一個表示上述 sql 的查詢。 到目前為止,我的理解是學說將根據實體中的 ORM 斷言自動獲取所需的關聯。 但是我不確定如何將其他實體帶入查詢中。 這是我到目前為止。

我在文章 repo 中的代碼是:

   $qb = $this->createQueryBuilder('ar')
            ->select('ar.title, ar.id, au.name')
            ->from('article_tags', 'at')
            ->innerJoin('tags', 't', 'WITH', 'at.tag_id = t.id')
            ->innerJoin('ar', 'WITH', 'at.article_id = ar.id')
            ->innerJoin('authors', 'au', 'WITH', 'au.id = ar.author_id')
            ->where('at.id IN (1,2)');

    return $qb->getQuery()->getResult();

我已經用“ON”和“WITH”關鍵字嘗試了上面的代碼。

我的錯誤是: [語義錯誤] line 0, col 76 near 'tags t WITH at.tag_id': Error: Class 'tags' is not defined。

當您使用 Doctrine ORM 進行連接時,您不需要指定連接條件,因為這應該在實體的元數據中。

因此,在您的實例中,您有與標簽和作者相關的文章,如果您想要標簽和作者以及您的文章,您的查詢應如下所示:

// this is in the article repository I'm guessing?
$qb = $this->createQueryBuilder('ar');
$qb->addSelect([ 't', 'au' ])
    ->join('ar.tags', 't')
    ->join('ar.authors', 'au')
    ->where($qb->expr()->in('a.tags', ':tags'))
    ->setParameter('tags', [ 1, 2 ]);

所以這兩個 join 語句是關於實體的屬性,在這種情況下是tagsauthors 在您的文章實體中,您需要根據文檔將它們設置為關聯。 元數據定義了文章如何與標簽和作者相關聯,Doctrine 將(通常)填補空白。 您的查詢看起來仍在 SQL 中思考,而不是實體和 Doctrine(和 DQL)。

附帶說明一下,上面的查詢並不是一個很好的查詢,因為返回的行數將等於標簽和作者的數量,您最好不要在選擇中添加額外實體的情況下進行查詢,然后之后抓取標簽(例如通過執行$article->getTags() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM