我正在尝试获取 Strip
实体中一对多 author
属性的内容。该关系位于 Account
和 Strip
实体之间,是双向的,并由 Strip
实体拥有。
这是我的代码:
Strip.php
/**
* Strip
*
* @ORM\Table(name="strip")
* @ORM\Entity(repositoryClass="AppBundle\Repository\StripRepository")
*/
class Strip
{
//...
/**
*
* @ORM\ManyToOne(targetEntity="Account", inversedBy="strips")
* @ORM\JoinColumn(name="author_id", referencedColumnName="id")
*/
private $author;
//...
}
Account.php
/**
* Account
*
* @ORM\Table(name="account")
* @ORM\Entity(repositoryClass="AppBundle\Repository\AccountRepository")
*/
class Account
{
//...
/**
* @var array
*
* @ORM\OneToMany(targetEntity="Strip", mappedBy="author")
*/
private $strips;
public function __construct() {
$this->strips = new ArrayCollection();
}
//...
}
当我尝试从 strip
获取 author
属性时,我得到一个具有正确 id
的空 account
code>,但其他字段为空(用户名
、slug
、...)。
例如,以下是 dump($strip->getAuthor())
返回的内容:
MyController.php on line 326:
Account {#773 ▼
+__isInitialized__: false
-id: 1
-username: null
-email: null
-emailIsPublic: 0
-password: null
-avatar: null
-biography: null
-level: 1
-registerDate: null
-strips: null
#slug: null
…2
}
以下是我的数据库的屏幕截图,显示该关系已正确注册:
数据库截图条表:
数据库截图账户表:
最佳答案
Doctrine2 使用延迟加载。
Whenever you have a managed entity instance at hand, you can traverse and use any associations of that entity that are configured LAZY as if they were in-memory already. Doctrine will automatically load the associated objects on demand through the concept of lazy-loading
嗨,这是 Doctrine 的一个懒惰行为...尝试输入您的:
/**
* @var array
*
* @ORM\OneToMany(targetEntity="Strip", mappedBy="author", fetch="EAGER")
*/
private $strips;
或者更好的解决方案在 StripRepository 中进行自定义查询并选择作者
$this->createQueryBuilder('s')
->addSelect('a')
->join('s.author', 'a')
关于php - Symfony3 : Relation One to Many return empty object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829279/