在两个表上使用左连接的Symfony2查询

时间:2014-01-24 20:07:57

标签: mysql symfony join doctrine-orm left-join

我正在尝试从查询中检索产品信息,该查询在一个表中查找标识符并在另一个表中匹配以获取产品ID,然后在产品表中查找以获取产品的信息。由于某种原因,我不能让这个查询运行成功。任何帮助我都非常感谢!!!

 $query = $em->createQuery('
            SELECT p
            FROM WIC\ProductBundle\Entity\Product p
            LEFT JOIN WIC\ListingBundle\Entity\Listing l
                ON l.product = p.id
            LEFT JOIN WIC\ListingBundle\Entity\ListingAma la
                ON la.id = l.id
            WHERE la.standardProductIdValue LIKE :stringValue
            AND   p.account = :account_id')
            ->setMaxResults(10)
            ->setParameter('stringValue', "%1234567890%")
            ->setParameter('account_id', $account_id); 

产品表

 |id|product_name      |account_id|
 ----------------------------------
 |1|Test Product 1     |74        | 
 |2|Test Product 2     |74        | 
 |3|Test Product 3     |74        | 
 |4|Test Product 4     |74        | 
 |5|Test Product 5     |74        | 

清单表

 |id|product_id       |
 ----------------------
 |1|1                 |
 |2|1                 |
 |3|2                 |
 |4|3                 |
 |5|1                 |
 |6|3                 |
 |7|5                 |

ListingAma表

 |id|standardProductIdValue |
 ----------------------------
 |1|1234567890              |
 |2|1234567890              |
 |3|AAAAAAAAAA              |
 |4|BBBBBBBBBB              |
 |5|1234567890              |
 |6|CCCCCCCCCC              |
 |7|0000000000              |

Listing和ListingAma表是基类(Listing)和扩展类(ListingAma),因此它们共享每个表中的ID号。

我想返回任何standardProductIdValue等于“1234567890”的查询的产品信息。在这种情况下,它应该检索行1,2和5,然后在列表中它应该与产品ID#1同步,然后返回“测试产品1”。

我上面的查询在Symfony中创建了这个错误:

 [Syntax Error] line 0, col 163: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON' (500 Internal Server Error)

感谢您的帮助!!!

2 个答案:

答案 0 :(得分:0)

尝试使用此查询:

    $query = $em->createQuery("
        SELECT p
        FROM WIC\ProductBundle\Entity\Product p
        LEFT JOIN WIC\ListingBundle\Entity\Listing l
            ON l.product = p.id
        LEFT JOIN WIC\ListingBundle\Entity\ListingAma la
            ON la.id = l.id
        WHERE la.standardProductIdValue LIKE :stringValue")
        ->setMaxResults(10)
        ->setParameter("stringValue", "%1234567890%"); 

这是否也因同样的错误而失败?

答案 1 :(得分:0)

感谢这篇文章,我能够找出问题所在:

http://stackoverflow.com/questions/20467428/error-expected-doctrine-orm-query-lexert-with-got-on

这是正确的代码:

$query = $em->createQuery('
        SELECT p
        FROM WIC\ProductBundle\Entity\Product p
        LEFT JOIN WIC\ListingBundle\Entity\Listing l
            WITH l.product = p.id
        LEFT JOIN WIC\ListingBundle\Entity\ListingAma la
            WITH la.id = l.id
        WHERE la.standardProductIdValue LIKE :stringValue
        AND   p.account = :account_id')
        ->setMaxResults(10)
        ->setParameter('stringValue', "%B00AM204Q6%")
        ->setParameter('account_id', $account_id);
相关问题