Bogdan  Dubyk
Bogdan Dubyk

Reputation: 5564

doctrine add foreign key but without creating association

In the current application we following DDD style and depend on DDD we have the aggregate scope and can't use other aggregates int that scope (we can use only id's of other aggregates if we need to make relations).

Example: we have User aggregate and we have Media aggregate, User can have an icon which is the relation to Media, but depends on DDD I can't make it like

/**
 * @OneToOne(targetEntity="Media")
 * @JoinColumn(name="icon_id", referencedColumnName="id")
 */
private $icon;

as in such case, I need to pass whole Media entity to User which is breaking DDD rule.

So to follow DDD rules I made it just as

/**
 * @var MediaId
 *
 * @ORM\Column(type="id", nullable=true)
 */
private $iconid;

but it's mean we can pass any id even not existed. For sure I can query DB to check if Media exist, but again it's breaking DDD rule as we can't make any action on Media aggregate when we have a deal with User aggregate.

So the question is can I somehow tell doctrine to add foreign key without creating an association? Or maybe I need to add foreign key manually through migrations?

Upvotes: 2

Views: 244

Answers (1)

Micaso
Micaso

Reputation: 56

You can do something like following in your setter:

public function setIcon($icon){
   if( ! ($icon instanceof Media) ){
       /** @var EntityManger $em get your EntityManager **/
       $icon = $em->getReference(Media::class, $icon)
   }

   $this->icon = $icon;
}

this will get you a proxy element so you can set the relation with that.

See: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#reference-proxies

and in the getter you can just return the id of the object

Upvotes: 0

Related Questions