[英]How can I fetch associated entities when fetching results as an array (hydrate array) via doctrine?
I am fetching data from the mysql database with doctrine:我正在使用学说从 mysql 数据库中获取数据:
$array = $this->em->getRepository(Documents::class)->findAll();
This is the output:这是输出:
For my case I want to fetch an array directly, so I created a function:对于我的情况,我想直接获取一个数组,所以我创建了一个函数:
$array = $this->em->getRepository(Documents::class)->getArray();
repository:存储库:
public function getArray()
{
return $this->getEntityManager()
->getRepository(Documents::class)
->createQueryBuilder('e')
->select('e')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
The array is created, but some fields are missing:数组已创建,但缺少某些字段:
How can I also fetch pages and products?我怎样才能获取页面和产品? And I would like my data to be shown as a date
+"timestamp": "02.12.2019"
我希望我的数据显示为日期
+"timestamp": "02.12.2019"
Forgot about core class that will require another setup忘记了需要另一个设置的核心类
Just use getArrayResult()
function instead of getResult()
.只需使用
getArrayResult()
函数而不是getResult()
。 It returns an array of all data它返回一个包含所有数据的数组
$query = $em->createQuery("SELECT test FROM namespaceTestBundle:Test test");
$tests = $query->getArrayResult();
Query#getResult(): Retrieves a collection of objects.
Query#getResult():检索对象集合。 The result is either a plain collection of objects (pure) or an array where the objects are nested in the result rows (mixed).
结果要么是一个简单的对象集合(纯),要么是一个数组,其中对象嵌套在结果行中(混合)。
Query#getArrayResult(): Retrieves an array graph (a nested array) that is largely interchangeable with the object graph generated by Query#getResult() for read-only purposes.
Query#getArrayResult():检索一个数组图(嵌套数组),该数组图在很大程度上可与 Query#getResult() 生成的对象图互换,用于只读目的。
I Just tested that returns all result of data as an array nested:我刚刚测试了将所有数据结果作为嵌套数组返回:
Second soluton in other answer will work as well but they works different ways:其他答案中的第二个解决方案也可以使用,但它们的工作方式不同:
Also see this answer https://stackoverflow.com/a/17499629/12232340 And repository另请参阅此答案https://stackoverflow.com/a/17499629/12232340和存储库
According to this EntityRepository class , findAll
don't take multiple arguments.根据这个EntityRepository 类,
findAll
不接受多个参数。
You need to do a "fetch-join" by adding it to the select:您需要通过将其添加到选择中来执行“获取连接”:
public function getArray()
{
return $this->getEntityManager()
->getRepository(Documents::class)
->createQueryBuilder('e')
->select('e', 'p')
->leftJoin('e.products', 'p')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
More info: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/dql-doctrine-query-language.html#joins更多信息: https : //www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/dql-doctrine-query-language.html#joins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.