php - Symfony3 : Relation One to Many return empty object

标签 php symfony doctrine-orm symfony-3.4

我正在尝试获取 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/

相关文章:

php - Symfony后台事件发送响应错误 session 后

php - Doctrine 无法坚持删除记录

php - Zend Framework 2 - Doctrine 2 - 如何处理 Zend 标准模型

javascript - 如何从所选项目选项中生成最常出现的值的递增列表?

php - wkhtmltopdf Knp-snappy 自定义高度/宽度需要哪个单位?

php - 使用 YML 设置实体字段默认值

php - 如何在没有 Doctrine 关系的情况下加入?

php - 使用 php 无法正确显示月份

php - 如何统计变量值是否重复?

Symfony2 缓存包(类似于 Zend Cache)