Symfony 5/原则:按创建日期时间对实体集合进行排序



我正在使用Symfony 5开发一个项目。我的一个用例涉及从数据库中读取一个集合,其中项目按创建顺序降序排列(最新的优先(。我正在使用";"可时间戳";从";stof/条令扩展捆绑包";以在我的实体中保存createdAt和updatedAt时间戳。

根据条令文档,我可以使用存储库方法对项目进行排序:

$sortedEntities = $repository->findBy(array('createdAt' => 'DESC'));

这就是有问题的属性:

/**
* @var DateTime $createdAt
*
* @GedmoTimestampable(on="create")
* @ORMColumn(type="datetime")
*/
private $createdAt;

然而,使用"ASC"或"DESC"似乎对列表的排序没有影响。

您没有正确阅读文档。orderBy是第二个参数,而不是第一个。文档中给出的例子是

$tenUsers = $em->getRepository('MyProjectDomainUser')->findBy(array('age' => 20), array('name' => 'ASC'), 10, 0);

在这里,您可以看到orderBy(name,ASC(是第二个参数。第一个arg是wherearg,在本例中为WHERE age = 20

这是DoctrinePersistenceObjectRepository的完整签名

/**
* Finds objects by a set of criteria.
*
* Optionally sorting and limiting details can be passed. An implementation may throw
* an UnexpectedValueException if certain values of the sorting or limiting details are
* not supported.
*
* @param array<string, mixed> $criteria
* @param string[]|null        $orderBy
* @param int|null             $limit
* @param int|null             $offset
* @psalm-param array<string, 'asc'|'desc'|'ASC'|'DESC'> $orderBy
*
* @return object[] The objects.
* @psalm-return T[]
*
* @throws UnexpectedValueException
*/
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null);

我希望这能为你澄清。:-(

[EDIT]针对您的注释,不能将true用作第一个参数的值。看看我贴的签名。第一个参数是@param array<string, mixed>,因此它需要一个数组。试试这个:

sortedEntities = $repository->findBy(array(), array('createdAt' => 'DESC'));

最新更新