geosocio/entity-attacher

Utility to Attach Doctrine Entities to existing instances

1.0.6 2018-02-18 16:45 UTC

This package is auto-updated.

Last update: 2024-11-12 01:29:52 UTC


README

Provides a method to attach related entities to the current unattached entity.This library is the product of a missing API that was found in doctrine/doctrine2#6459. If you want to create a new entity with a lot of existing related entities, you would have to manually go through each relation and attach the related entities.

This can be tedious for entities that have a large number of relationships.

Configuration

Add something like this to your service configuration:

app.entity_attacher:
        class: GeoSocio\EntityAttacher\EntityAttacher
        arguments:
            - '@doctrine.orm.entity_manager'
            - '@annotations.reader'

You may also need to add the GeoSocio\EntityAttacher\Annotation\Attach annotation to your annotation reader.

Usage

Add the @Attach annotation to the relationships that should be attached.

/**
 * @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;
}

Then when a new Post is created, you can attach the entity:

$post = $this->attacher->attach($post);

Doing this will retrieve the $user from the database and prevent the A new entity was found through the relationship error. If you still receive that error, it means the $user was not found (and thus, should be persisted).