Gabriel Diaconescu
Gabriel Diaconescu

Reputation: 1799

Symfony2 map entity to different tables

I have my entity foo which contains the properties id, bar and baz. Can I populate two different tables (like foo1 and foo2) with the same entity, based on the property baz which is not mapped. The code of the entity looks like this :

class foo {

  /**
  * @ORM\Column(name="id", type="integer")
  * @ORM\Id
  */      
  private $id;

  /**
  * @ORM\Column(name="bar", type="string")
  */
  private $bar;

  /**
  * Property not mapped in the database
  */
  private $baz; 
}

I want if the value of baz is 1, to save the entity in the table foo1, and if the value of baz is 2, to save in the table foo2. Where can I select in which table it would save ?

Upvotes: 3

Views: 1938

Answers (2)

MisterJ
MisterJ

Reputation: 929

Do you absolutely need your $baz attribute ? and how do you determine it?

Because a simple solution that might help you is to make an abstract foo class, and then 2 classes that inherit from it and that do the database's relation.

Here is the example :

abstract class foo {

  /**
  * @ORM\Column(name="id", type="integer")
  * @ORM\Id
  */      
  protected $id;

 /**
 * @ORM\Column(name="bar", type="string")
 */
 protected $bar;
}


/* @ORM\Table(name="foo1")
* @ORM\Entity(repositoryClass="yourRepo")
*/
foo1 extends foo{
}

/* @ORM\Table(name="foo2")
* @ORM\Entity(repositoryClass="yourRepo")
*/
foo2 extends foo{
}

Though I'm not sure it works as simply as this but maybe it could help.

Some documentation that might help doing this : http://docs.doctrine-project.org/en/2.0.x/reference/inheritance-mapping.html

Please feel free to edit/correct, I'm pretty new in this but I think the idea might help .

Upvotes: 0

Baba Yaga
Baba Yaga

Reputation: 1819

Use doctrine inheritance:

Doctrine inheritance

It works like this:

BaseClient

  • SubClient1 extends from BaseClient
  • SubClient2 extends from BaseClient

Like that you can even add extra fields to let's say SubClient1 or SubClient2 who are specific only for that entity.

Upvotes: 3

Related Questions