如何在 EasyAdmin 中用户可以看到自己的产品,而管理员可以看到所有产品?

How user can se own product in EasyAdmin but admin can se all products?

我在我的 Symfony 项目中使用 EasyAdmin 3,我对 easyAdmin 的问题是,我有两个角色,角色管理员和角色艺术家。 我发现每个人如何使用自己发布的产品,但我希望管理员能看到每个人的所有产品, 我的意思是美工一定要在easyadmin看到自己的产品,admin才能看到大家的产品?

如果有人伸出援手,我将不胜感激

<?php

namespace App\Controller\Admin;


use App\Entity\Product;

use Doctrine\ORM\QueryBuilder;


use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\SlugField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;

class ProductCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Product::class;
    }

    public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
    {
        $user = $this->getUser()->getId();
        $qb = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
        $qb->where('entity.user = :id');
        $qb->setParameter('id', $user);

        return $qb;
    }

谢谢哈米德

根据用户角色,您必须添加或不添加用户 ID 的 where 条件。 所以如果用户是admin,不要添加where条件。否则,添加 where 条件。

测试用户角色,可以调用$this->isGranted('ROLE_ADMIN')

会是这样的:

public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
    $user = $this->getUser()->getId();
    $qb = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
    if (!$this->isGranted('ROLE_ADMIN')) {
       $qb->where('entity.user = :id');
       $qb->setParameter('id', $this->getUser()->getId());
    }
    return $qb;
}