简体   繁体   English

ZF2 Doctrine2存储库结果作为数组

[英]ZF2 Doctrine2 repository result as array

I have the problem, that I have two controllers. 我有一个问题,我有两个控制器。 One is a restful controller which only handles json data and returns a JsonModel , and the other one is a default controller which returns a ViewModel Now I have the problem, that my method only returns an array of entities, which is correct for the default controller, but my restful controller needs the entities as an array. 一个是一个宁静的控制器,它仅处理json数据并返回JsonModel ,另一个是默认的控制器,它返回一个ViewModel现在我有一个问题,我的方法只返回一个实体array ,这对于默认控制器是正确的,但是我的控制器需要将实体作为数组。 How can I handle this? 我该如何处理?

MealController 膳食控制器

class MealController extends AbstractRestfulController {
    protected $mealService;

    public function getList() {
        $meals = $this->mealService->getAllMeals();

        return new JsonModel($meals);
    }
}

MealService 餐饮服务

class MealService {
    protected $mealRepository;

    public function getAllMeals() {
        return $this->mealRepository->findAll();
    }
}

MealRepository 餐库

class MealRepository extends EntityRepository {
    public function findAll() {
        $queryBuilder = $this->createQueryBuilder('meal')
            ->orderBy('title');

        return $queryBuilder->getQuery()->getResult();
    }
}

You coud use for that Array Hydration . 您可以使用该数组水化技术 It allows to specify a hydration mode when executing queries, and change the data type of the results returned. 它允许在执行查询时指定水合模式,并更改返回结果的数据类型。 You just need to use the constant Query::HYDRATE_ARRAY as parameter in your getResult() method : 您只需要在getResult()方法中使用常量Query::HYDRATE_ARRAY作为参数:

public function findAll() {
    $queryBuilder = $this->createQueryBuilder('meal')
        ->orderBy('title');

    return $queryBuilder->getQuery()->getResult(Doctrine\ORM\Query::HYDRATE_ARRAY);
}

Maybe you could also take a look at the EntitySerializer class which let you create an array of json from an entity : 也许您还可以看看EntitySerializer类,该类使您可以从实体创建json数组:

$entitySerializer = new EntitySerializer($em);
$entityAsArray = $entitySerializer->toArray($entity);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM