EasyCorp / EasyAdminBundle

EasyAdmin is a fast, beautiful and modern admin generator for Symfony applications.
MIT License
3.99k stars 1.01k forks source link

Allow map calculated DB field to entity property #6263

Open zorn-v opened 4 weeks ago

zorn-v commented 4 weeks ago

Imagine that you want to restrict delete action on entities with relation by other entities. And you don't want/can't use cascade behavior. In such case you need to do additional query (or maybe much more if relation has fetch eager fields) for every entity in index page.

With proposed fix you can addSelect in createIndexQueryBuilder and it will be mapped correctly. For example you have Category and Product and want to restrict delete category if it has products. As bonus you can get product count in category within one query. Like

// Category entity
public $productsCount;
//Category crud controller
    public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
    {
        $qb = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);

        $qb->leftJoin('entity.products', 'p')->addSelect('COUNT(p.id) AS productsCount');

        return $qb;
    }