在我的“父”实体中,我有一个 OneToMany“子”属性。 我想订购“孩子”的号码。有什么推荐的方法吗?
谢谢!
我的要求更具体一些。在管理中,我必须始终按产品数量订购资源。 以防万一其他人遇到这个问题:
自定义过滤器如下所示:
namespace App\Filter;
use ApiPlatform\Core\Bridge\Doctrine\Common\Filter\SearchFilterInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use App\Entity\Product;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\PropertyInfo\Type;
final class ProductsCountFilter extends AbstractContextAwareFilter implements SearchFilterInterface
{
protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
{
if ($property === 'order') {
$queryBuilder
->leftJoin(Product::class, "p", "WITH", "p.advertiser = o.id")
->groupBy('o.id')
->orderBy("COUNT(p.advertiser)", "DESC");
}
}
// This function is only used to hook in documentation generators (supported by Swagger and Hydra)
public function getDescription(string $resourceClass): array
{
if (!$this->properties) {
return [];
}
$description = [];
foreach ($this->properties as $property => $strategy) {
$description["ProductsCount_$property"] = [
'property' => $property,
'type' => Type::BUILTIN_TYPE_STRING,
'required' => false,
'swagger' => [
'description' => 'Count by number of products.',
'name' => 'Products Filter',
],
];
}
return $description;
}
}
现在我们必须将其应用到 GET 方法的集合中:
#[ApiResource(
normalizationContext: ['groups' => ['read:advertiser']],
denormalizationContext: ['groups' => ['write:advertiser']],
collectionOperations: [
'get' => [
'filters' => [ProductsCountFilter::class]
]
],
)]
研究: 您可以在此处阅读有关过滤器的更多信息:https://api-platform.com/docs/core/filters/
可以在那里找到回复
对我有用的代码
要从结果中隐藏附加字段,您可以将其声明为隐藏。这样您就可以按顺序使用它,而无需将其包含在结果中。
$qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');