Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何通过加入条令填充附加字段_Php_Mysql_Join_Doctrine Orm_Field - Fatal编程技术网

Php 如何通过加入条令填充附加字段

Php 如何通过加入条令填充附加字段,php,mysql,join,doctrine-orm,field,Php,Mysql,Join,Doctrine Orm,Field,假设我有一个具有多通关系(带有额外的_LAZY)的实体,显然还有一个连接列 eg. Article (main entity) -> Author (external entity) 假设我向未映射到ORM的文章中添加了一个字段author\u name,并且在某些上下文中,该字段应该包含Article->author->name值(通常可以保持空值) 当我查询文章列表时,我希望自动填充该文章作者的名称,而不实现对查询结果的每个元素执行选择的getter。我想在原始查询中通过一个简单的连

假设我有一个具有多通关系(带有额外的_LAZY)的实体,显然还有一个连接列

eg. Article (main entity) -> Author (external entity)
假设我向未映射到ORM的文章中添加了一个字段
author\u name
,并且在某些上下文中,该字段应该包含
Article->author->name
值(通常可以保持空值)

当我查询文章列表时,我希望自动填充该文章作者的名称,而不实现对查询结果的每个元素执行选择的getter。我想在原始查询中通过一个简单的连接获取并补充该值

我不想将fetch模式设置为渴望性能,因为在我的项目中,Author是一个非常复杂的实体

这可能吗


谢谢

也许我已经找到了解决办法。不知道这是否是最好的方法,但它是有效的

我已经添加到主要的a类字段getter

public getAuthorName() {
  return $this->author->name
}
在我的上下文中,只有在特定条件下序列化程序才会调用此getter

在我的存储库代码中,我有一个特殊的方法(我对其进行了重构,以便任何方法都可以隐式调用它),用于在查询时强制填充Article->author字段。该方法只需使用querybuilder向Author类添加左连接,并临时将FetchMode设置为EAGER on Article->Author

最后,一个简单的存储库方法可能是这样的

public findAllWithCustomHydration() {
    $qb = $this->createQueryBuilder('obj');
    $qb->leftJoin("obj.author", "a")
       -> addSelect("a"); //add a left join and a select so the query automatically retrive all needed values to populate Article and Author entities
    //you can chain left join for nested entities like the following
    //->leftJoin("a.address", "a_address")
    //-> addSelect("a_address");


    $q = $qb->getQuery()
              ->setFetchMode(Article::class, "author", ClassMetadata::FETCH_EAGER);
   //setFetchMode + EAGER tells Doctrine to prepopulate the entites NOW and not when the getter of  $article->author is called. 
   //I don't think that line is strictly required because Doctrine could populate it at later time from the same query result or maybe doctrine automatically set the field as EAGER fetch when a LEFT JOIN is included in the query, but i've not yet tested my code without this line.

    return $q->getResult();
}
缺点是您必须自定义每个查询,或者更好地为repo的每个方法使用DQL/SQL/QueryBuilder,但是通过良好的重构,对于简单的包含情况,您可以编写一个通用方法,在字段名数组的基础上注入该连接

希望这对你有所帮助,如果你找到更好的方法,请添加你的答案


另外,我已经在运行中编写了上述代码,因为现在我不在笔记本上,希望它在第一次执行时能正常工作。

我今天检查了所有条令注释,没有发现任何允许您这样做的注释。