Symfony中如何在多对多关系中排序



我有两个表productscategories。产品可以有很多类别,类别可以有很多产品。(这两个表之间的关系是many-to-many(

为了映射这两个表之间的关联,我创建了另一个存储product_idcategory_id的新表product_categories

以下是我在实体中用于连接这三个表的注释。

产品实体

/**
* @var DoctrineCommonCollectionsCollection
*
* @ORMManyToMany(targetEntity="Category", mappedBy="products")
*/
private $categories;

类别实体

/**
* @var DoctrineCommonCollectionsCollection
*
* @ORMManyToMany(targetEntity="Product", inversedBy="categories")
* @ORMJoinTable(name="product_categories",
*   joinColumns={
*     @ORMJoinColumn(name="category_id", referencedColumnName="id")
*   },
*   inverseJoinColumns={
*     @ORMJoinColumn(name="product_id", referencedColumnName="id")
*   }
* )
*/
private $products;

现在的问题是,我想将product_categories中的记录按一定的顺序排序。所以我在product_categories表中添加了一个名为serial_number的新列。

我试图实现的结果是,当我使用$product->getCategories()检索产品的类别时,生成的类别数组应该按serial_number排序。

我尝试了以下注释。

/**
* @var DoctrineCommonCollectionsCollection
*
* @ORMManyToMany(targetEntity="Product", inversedBy="categories")
* @ORMJoinTable(name="product_categories",
*   joinColumns={
*     @ORMJoinColumn(name="category_id", referencedColumnName="id")
*   },
*   inverseJoinColumns={
*     @ORMJoinColumn(name="product_id", referencedColumnName="id")
*   }
* )
* @OrderBy({"product_categories.serial_number"="DESC"})
*/
private $products;

但这会导致注释语法错误。

致命错误:Unaught Doctrine\Common\Annotations\AnnotationException:[语义错误]注释"OrderBy";在属性ProductBundle\Entity\Product:中:$products从未导入。你可能忘记加一个";使用";这个注释的语句?在第54行上的/var/www/sonicwall.local/app/vendor/doctrine/annotations/lib/doctrine/Common/annotations/AnnotationException.php中

当我使用@ORMOrderBy({"product_categories.serial_number"="DESC"})时,我不会得到语法错误,但结果也不会排序。

我的问题是,有没有一种方法可以使用注释实现这一点,而不必为product_categories表创建新的实体和存储库?

您必须使用@ORM\OrderBy:

@OrderBy acts as an implicit ORDER BY clause for the given fields, that is appended to all the explicitly given ORDER BY items.
All collections of the ordered type are always retrieved in an ordered fashion.
To keep the database impact low, these implicit ORDER BY items are only added to a DQL Query if the collection is fetch joined in the DQL

查询。

/**
* @var DoctrineCommonCollectionsCollection
*
* @ORMManyToMany(targetEntity="Product", inversedBy="categories")
* @ORMJoinTable(name="product_categories",
*   joinColumns={
*     @ORMJoinColumn(name="category_id", referencedColumnName="id")
*   },
*   inverseJoinColumns={
*     @ORMJoinColumn(name="product_id", referencedColumnName="id")
*   }
* )
* @ORMOrderBy({"serialNumber"="DESC"})
*/
private $products;

您尝试过做类似的事情,但使用了product_categories.serial_number。您不需要product_categories,因为order by将尝试使用自己的字段对集合中的每个成员进行排序。因此,只需编写serialNumber,就会根据每个产品序列号进行排序。

然而,我刚刚看到您已经在注释中尝试了类似的操作,因此请确保使用属性名称作为字段:serialNumberserial。。。如$serialNumber所示

最新更新