I'm implementing a REST API, and I would like to implement a quick and easy way to create and persist entities.
Therefore, I created an entity like so, where $plain
is a basic associative array:
public function __construct($plain = null)
{
if ($plain != null) {
foreach ($plain as $k => $v) {
if (property_exists($this, $k))
$this->{$k} = $v;
else
throw new Exception("Property $k does not exist in " . self::class);
}
}
}
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
*/
private $parent;
My frontend input will look something like this, and then decoded into the $plain
array from above:
{
"name": "FooBar",
"parent": 1
}
When flushing, I'm greeted by a totally understandable Doctrine error, telling me that $parent
is an integer and is not an entity as expected.
I'd like to mention that here, the "parent" will never be fetched by the backend, as I'm creating a new entity, all I want to do is write 1
in the parent_id
column of my database.
To summarize, my goal is to make doctrine write the id in the database column, without checking for context.
Any idea? Thanks!
Using GraphQl is the way to go!
To properly answer the question. Using references is the key:
$em->getReference(Entity::class, 1);