Symfony2, Doctrine2 - 按类别和查询显示项目

2022-01-03 00:00:00 php symfony doctrine-orm

我正在创建第二个路由,用于在 URL 中按类别显示所有文章.这是我的路线:

I'm creating second route for display all articles by category in the URL. There is my route for that:

default_blog_category:
    path:     /category/{slug}/{page}
    defaults: { _controller: AcmeBlogBundle:Default:indexByCategory, page: 1 }

这是我的尝试,按类别获取项目,但它不起作用(我会收到此错误消息:

And here is my try, to get items by category, but it does not works (I'll get this error message:

[Semantical Error] line 0, col 47 near 'categories =': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

):

public function indexByCategoryAction($slug, $page)
{
    $em = $this->getDoctrine()->getManager();
    $dql = "SELECT a FROM AcmeBlogBundle:Article a WHERE a.categories = :category ORDER BY a.published DESC";
    $query = $em->createQuery($dql)->setParameter('category', $slug);

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $this->get('request')->query->get('page', $page),
        10
    );

    return $this->render('AcmeBlogBundle:Default:index.html.twig', array('pagination' => $pagination));
}

我不确定,现在如何在查询中使用 WHERE,这也是我的 Article.php 实体:

I'm not sure, how to use WHERE in my query for now, here is also my Article.php entity:

<?php

namespace AcmeBlogBundleEntity;

use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
use GedmoMappingAnnotation as Gedmo;

/**
 * @ORMEntity(repositoryClass="AcmeBlogBundleEntityArticleRepository")
 * @ORMTable(name="articles") 
 */
class Article
{
    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;              

    /**
     * @ORMColumn(type="string", length=200)    
     * @AssertNotBlank(
     *      message = "Title cannot be blank"      
     * )    
     * @AssertLength(
     *      min = "3",
     *      minMessage = "Title is too short"         
     * )     
     */     
    private $title;

    /**
     * @GedmoSlug(fields={"title"}, updatable=true, separator="-") 
     * 
     * @ORMColumn(name="slug", type="string", length=200, nullable=false, unique=true)
     */
    private $slug;

    /**
     * @ORMColumn(type="datetime")    
     * @AssertNotBlank(
     *      message = "DateTime cannot be blank"
     * )
     * @AssertDateTime(
     *      message = "DateTime is not valid"
     * )     
     */
    protected $published;

    /**
     * @ORMManyToMany(targetEntity="Category", inversedBy="articles")
     * @AssertCount(min = 1, minMessage = "Choose any category") 
     */
    private $categories;

    /**
     * @ORMOneToMany(targetEntity="Comment", mappedBy="article")
     * @ORMOrderBy({"published" = "ASC"})     
     */
    private $comments;                       

    /**
     * @ORMColumn(type="text")
     * @AssertNotBlank(
     *      message = "Perex cannot be blank"      
     * )    
     * @AssertLength(
     *      min = "5",
     *      minMessage = "Perex is too short"         
     * )     
     */
    private $perex;

    /**
     * @ORMColumn(type="text")
     * @AssertNotBlank(
     *      message = "Content cannot be blank"      
     * )    
     * @AssertLength(
     *      min = "10",
     *      minMessage = "Content must have min. 10 characters"         
     * )     
     */
    private $content;

    /**
     * @ORMColumn(type="string", length=200)     
     */     
    private $description;

    /**
     * @ORMColumn(type="string", length=200)     
     */     
    private $keywords;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->categories = new DoctrineCommonCollectionsArrayCollection();
        $this->comments = new DoctrineCommonCollectionsArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Article
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string 
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Article
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string 
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set content
     *
     * @param string $content
     * @return Article
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string 
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Add categories
     *
     * @param AcmeBlogBundleEntityCategory $categories
     * @return Article
     */
    public function addCategory(AcmeBlogBundleEntityCategory $categories)
    {
        //$this->categories[] = $categories;

       //return $this;
       if (!$this->categories->contains($categories)) {
            $this->categories->add($categories);
            $categories->addArticle($this);
        }
    }

    /**
     * Remove categories
     *
     * @param AcmeBlogBundleEntityCategory $categories
     */
    public function removeCategory(AcmeBlogBundleEntityCategory $categories)
    {
        $this->categories->removeElement($categories);
    }

    /**
     * Get categories
     *
     * @return DoctrineCommonCollectionsCollection 
     */
    public function getCategories()
    {
        return $this->categories;
    }

    /**
     * Add comments
     *
     * @param AcmeBlogBundleEntityComment $comments
     * @return Article
     */
    public function addComment(AcmeBlogBundleEntityComment $comments)
    {
        $this->comments[] = $comments;

        return $this;
    }

    /**
     * Remove comments
     *
     * @param AcmeBlogBundleEntityComment $comments
     */
    public function removeComment(AcmeBlogBundleEntityComment $comments)
    {
        $this->comments->removeElement($comments);
    }

    /**
     * Get comments
     *
     * @return DoctrineCommonCollectionsCollection 
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * Set published
     *
     * @param DateTime $published
     * @return Article
     */
    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }

    /**
     * Get published
     *
     * @return DateTime 
     */
    public function getPublished()
    {
        return $this->published;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Article
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set keywords
     *
     * @param string $keywords
     * @return Article
     */
    public function setKeywords($keywords)
    {
        $this->keywords = $keywords;

        return $this;
    }

    /**
     * Get keywords
     *
     * @return string 
     */
    public function getKeywords()
    {
        return $this->keywords;
    }

    /**
     * Set perex
     *
     * @param string $perex
     * @return Article
     */
    public function setPerex($perex)
    {
        $this->perex = $perex;

        return $this;
    }

    /**
     * Get perex
     *
     * @return string 
     */
    public function getPerex()
    {
        return $this->perex;
    }
}

有什么想法吗?

推荐答案

您必须加入类别.此代码应放置在 ArticleRepository 中.

You have to join the categories. This code should be placed in the ArticleRepository.

$qb = $this->createQueryBuilder('a');
$qb->add('select', 'a');
$qb->leftJoin('a.category', 'c');
$qb->where('c.name LIKE :category'); /* i have guessed a.name */
$qb->setParameter('category', $slug);
$qb->getQuery()->getResult();

参见 doctrine 查询构建器 和 symfony 自定义存储库类 教程.

相关文章