gpt4 book ai didi

php - Symfony3 : Relation One to Many return empty object

转载 作者:行者123 更新时间:2023-12-02 03:40:23 25 4
gpt4 key购买 nike

我正在尝试获取 Strip 实体中一对多 author 属性的内容。该关系位于 AccountStrip 实体之间,是双向的,并由 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
}

以下是我的数据库的屏幕截图,显示该关系已正确注册:

数据库截图条表: Database screenshot strip table

数据库截图账户表: Database screenshot account table

最佳答案

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com