Case:
I have plenty of entities in the system. I also have entity_alias table which consist of two fields: alias (pk), entity_id. (NOTE: in my database all the entities have a unique id across the whole database, that is why I do not have entity_type field in entity_alias table).
Goal:
Create a trait which can be used to any entity and which provides an ability to set, get and drop alias for an entity.
Code example:
Alias entity:
/**
* Class Alias
*
* @ORM\Entity()
* @ORM\Table("entity_alias")
* @UniqueEntity("entityId")
*/
class Alias
{
/**
* @var string
* @Assert\NotBlank()
* @ORM\Column(type="bigint", nullable=false)
*/
private $entityId;
/**
* @var string
*
* @ORM\Id
* @ORM\Column(type="string", nullable=false)
*/
private $alias;
/**
* Alias constructor.
*
* @param $objectId
* @param $alias
*/
public function __construct($objectId, $alias)
{
$this->alias = $alias;
$this->objectId = $objectId;
}
/**
* @return mixed
*/
public function __toString()
{
$sting = $this->alias;
return (string) $sting;
}
}
AliasableTrait:
trait AliasableTrait
{
/**
* @ORM\OneToOne(targetEntity="Alias", cascade={"persist", "remove"}, orphanRemoval=true)
* @ORM\JoinColumn(name="id", referencedColumnName="entity_id", onDelete="CASCADE")
* @var Alias
*/
protected $alias;
/**
* @return string|int
*/
abstract public function getId();
/**
* @param string $alias
*/
public function setAlias(string $alias)
{
$this->alias = new Alias($this->getId(), $alias);
}
/**
* @return string
*/
public function getAlias() : string
{
return (string) $this->alias;
}
public function dropAlias()
{
$this->alias = null;
}
}
Right now I am getting Missing value for primary key alias on Alias.
Case: I have plenty of entities in the system. I also have
entity_alias
table which consist of two fields: alias (pk), entity_id. (NOTE: in my database all the entities have a unique id across the whole database, that is why I do not have entity_type field inentity_alias
table).Goal: Create a trait which can be used to any entity and which provides an ability to set, get and drop alias for an entity.
Code example: Alias entity:
AliasableTrait:
Right now I am getting Missing value for primary key alias on Alias.
Question: Is it possible to do?