hun*_*rix 2 php symfony doctrine-orm symfony-3.4
author
我正在尝试获取实体中一对多属性的内容Strip
。该关系是实体Account
与实体之间的Strip
、双向的、并且由实体所拥有Strip
。
这是我的代码:
\n剥离.php
\n/**\n* Strip\n*\n* @ORM\\Table(name="strip")\n* @ORM\\Entity(repositoryClass="AppBundle\\Repository\\StripRepository")\n*/\nclass Strip\n{\n//...\n /**\n *\n * @ORM\\ManyToOne(targetEntity="Account", inversedBy="strips")\n * @ORM\\JoinColumn(name="author_id", referencedColumnName="id")\n */\n private $author;\n//...\n}\n
Run Code Online (Sandbox Code Playgroud)\n帐户.php
\n/**\n * Account\n *\n * @ORM\\Table(name="account")\n * @ORM\\Entity(repositoryClass="AppBundle\\Repository\\AccountRepository")\n */\nclass Account\n{\n //...\n /**\n * @var array\n *\n * @ORM\\OneToMany(targetEntity="Strip", mappedBy="author")\n */\n private $strips;\n\n public function __construct() {\n $this->strips = new ArrayCollection();\n }\n //...\n}\n
Run Code Online (Sandbox Code Playgroud)\nauthor
当我尝试从 a获取属性时strip
,account
右侧为空id
,但其他字段(username
、slug
、...)为空。
例如,adump($strip->getAuthor())
返回的内容如下:
MyController.php on line 326:\nAccount {#773 \xe2\x96\xbc\n +__isInitialized__: false\n -id: 1\n -username: null\n -email: null\n -emailIsPublic: 0\n -password: null\n -avatar: null\n -biography: null\n -level: 1\n -registerDate: null\n -strips: null\n #slug: null\n \xe2\x80\xa62\n}\n
Run Code Online (Sandbox Code Playgroud)\n以下是我的数据库的屏幕截图,显示该关系已正确注册:
\n数据库截图条表:\n
数据库截图帐户表:\n
Doctrine2 使用延迟加载。
只要您手头有托管实体实例,您就可以遍历并使用该实体的任何配置为 LAZY 的关联,就好像它们已经在内存中一样。Doctrine会通过延迟加载的概念自动按需加载关联对象
嗨,这是 Doctrine 的懒惰...尝试输入您的:
/**
* @var array
*
* @ORM\OneToMany(targetEntity="Strip", mappedBy="author", fetch="EAGER")
*/
private $strips;
Run Code Online (Sandbox Code Playgroud)
或者更好的解决方案在 StripRepository 中进行自定义查询并选择作者
$this->createQueryBuilder('s')
->addSelect('a')
->join('s.author', 'a')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1292 次 |
最近记录: |