Error: Invalid PathExpression. Must be a StateFieldPathExpression.

Error: Invalid PathExpression. Must be a StateFieldPathExpression.

我正在研究 symfony 项目实体与查询生成器。当我尝试 运行 这个函数时,我遇到了这个问题。

[Semantical Error] line 0, col 9 near 'category FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

public function json_filterAllproductsAction() {

    $search = "";
    $category = 1;

    //Combine tables and create the query with querybuilder
    $em = $this->container->get('doctrine.orm.entity_manager');

    $qb = $em->createQueryBuilder();

    $qb->select('p.category')
            ->from('EagleAdminBundle:Products', 'p')
            ->orderBy('p.id', 'DESC');
    if ($category != 0) {
        $qb->andWhere('p.category = :category')
                ->setParameter('category', $category);
    }
    $qb->andWhere('p.productTitle LIKE :title')
            ->setParameter('title', "$search%");

    //convert to json using "JMSSerializerBundle"
    $serializer = $this->container->get('serializer');
    $jsonproducts = $serializer->serialize($qb->getQuery()->getResult(), 'json');
    return new Response($jsonproducts);
}

我认为错误在于,

$qb->select('p.category')

如果有人能帮助我,那就太好了。

您还需要在加入中获取类别。像这样的东西应该可以正常工作:

    $qb->select('p', 'c')
        ->from('EagleAdminBundle:Products', 'p')
        ->orderBy('p.id', 'DESC')
        ->join('p.category', 'c');

    if ($category != 0) {

        $qb->andWhere('p.category = :category')
            ->setParameter('category', $category);
    }

    $qb->andWhere('p.productTitle LIKE :title')
        ->setParameter('title', "$search%");

请注意,如果您不想将搜索限制为仅具有类别的产品,您可以将连接更改为 leftJoin。

另请注意,您可以将序列化程序配置为序列化产品类别 属性。然后您应该能够获取产品并让它自动为您序列化类别。