Error: Invalid PathExpression. Must be a StateFieldPathExpression.

安稳与你 提交于 2019-12-24 14:34:59

问题


I'm working on a symfony project entity with query builder. When I try to run this function I get this issue.

[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);
}

I think error is in,

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

It would be great help someone can help me.


回答1:


You need to fetch category as well in your join. Something like this should work fine:

    $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%");

Note if you don't want to limit your search to only products that have categories you can change the join to a leftJoin.

Also note you can have the serializer configured to serialize the category property of product. Then you should just be able to fetch a product and have it automatically serialize the category for you.



来源:https://stackoverflow.com/questions/34408073/error-invalid-pathexpression-must-be-a-statefieldpathexpression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!