geosocio / entity-attacher
将 Doctrine 实体附加到现有实例的实用工具
1.0.6
2018-02-18 16:45 UTC
Requires
- doctrine/annotations: ^1.0
- doctrine/collections: ^1.0
- doctrine/orm: ^2.4.0
Requires (Dev)
- phpunit/phpunit: ^6.2
- squizlabs/php_codesniffer: ^3.0
README
提供了一种将 相关 实体附加到当前 未附加 实体的方法。这个库是发现于 doctrine/doctrine2#6459 的缺失 API 的产物。如果你想要创建一个包含大量现有相关实体的新实体,你必须手动遍历每个关系并将相关实体附加。
对于具有大量关系的实体来说,这可能是一件繁琐的事情。
配置
在你的服务配置中添加类似以下内容
app.entity_attacher: class: GeoSocio\EntityAttacher\EntityAttacher arguments: - '@doctrine.orm.entity_manager' - '@annotations.reader'
你可能还需要将 GeoSocio\EntityAttacher\Annotation\Attach
注解添加到你的注解读取器。
用法
将 @Attach
注解添加到需要附加的关联关系中。
/** * @ORM\Entity() * @ORM\Table(name="post") */ class Post { /** * @ORM\ManyToOne(targetEntity="GeoSocio\Core\Entity\User\User") * @ORM\JoinColumn(name="user_id", referencedColumnName="user_id") * @Attach() */ private $user; }
然后,当你创建一个新的 Post
时,你可以附加该实体
$post = $this->attacher->attach($post);
这样做将从数据库中检索 $user
并防止出现 A new entity was found through the relationship
错误。如果你仍然收到该错误,这意味着 $user
未找到(因此,应该持久化)。