doctrine2 date/datetime as ID - symfony

is it possible to set an attribute as an id when the column is date or datetime?`
Here my Attribute in the entity:
/**
* #var date $statisticdate
*
* #ORM\Column(name="statisticdate", type="date", nullable=false, unique=true)
* #Id
* #Assert\DateTime()
*/
private $statisticdate;
When i'm persisting a new object, i have an error that the object Datetime cannot be converted to string.
Now i created a normal id attribut and everything works.
Thank you very much.

Asfar as I know, it is only allowed in a composite key, and even that is has some known issues. I think the easy solution can be to make it a string and let the setStaticdate($datetime) check wheather it is a valid date or not.

Related

making unique Constraint on doctorine2

I would like to make uniqueConstraint user and lesson.
/**
* #ORM\Table(name="ReviewSchool",uniqueConstraints={
* #ORM\UniqueConstraint(name="lessonid", columns={"lesson", "user"})})
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class ReviewSchool
{
* #ORM\ManyToOne(targetEntity="Lesson",inversedBy="reviewschool")
* #ORM\JoinColumn(name="review_lesson", referencedColumnName="id",onDelete="cascade")
*/
private $lesson;
/**
*
* #ORM\ManyToOne(targetEntity="User",inversedBy="reviewschool")
* #ORM\JoinColumn(name="review_user",referencedColumnName="id",onDelete="cascade")
*/
private $user;
However it shows
[Doctrine\DBAL\Schema\SchemaException]
There is no column with name 'lesson' on table 'ReviewSchool'.
Surely I have 'lesson' column, how can I solve this?
I have misunderstood something??
It allows to hint the SchemaTool to generate a database unique constraint on the specified table columns. It only has meaning in the SchemaTool schema generation context.
So you have to use column names. In your case:
#ORM\UniqueConstraint(columns={"review_lesson", "review_user"})}

Symfony 2 Doctrine unique id from another source

I'm pulling a lot of data to cache locally, the data i pull is in json format and has along with it Unique Id's for each record.
Is there a way i can tell doctrine to use this as the id for the table?
I'm only going to be populating these tables with data from my json, i wont be adding any new records from other sources only from my json pull.
is it possible to get doctrine to use a field from my json pull as the primary key?.
when i use doctrine:generate:entity
it automatically adds an id field I would ideally like to get rid of this and use the uniqueID column from my data pull. ($teamKey)
say for example this is my entity
/**
* Team
*
* #ORM\Table("fp_team)
* #ORM\Entity(repositoryClass="FantasyPro\DataBundle\Entity\TeamRepository")
*/
class Team
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="teamKey", type="string", length=50, nullable=false)
*/
private $teamKey;
/**
more properties ...........
*/
is it just a case of deleting the existing $id property and modifying my $teamKey property to:
/**
* #var string
* #ORM\Id
* #ORM\Column(name="teamKey", type="string", length=50, unique=true, nullable=false)
*/
private $teamKey;
Is it more complex than that or not possible?
does the unique id field for doctrine have to be called $id ?
Theoretically, it depends on your DB. But, generally speaking, any DB type should let you set any ID you want.
So, you can always do $entity->setId() any time you want, and persist it with that ID, with no problem.

Symfony2 & FOSRestBundle: Getting UUID packed in a BINARY(16) field from MySQL

I am facing a weird problem relating to UUIDs.
I have developed a REST API using Symfony2+FOSRestBundle+JMSSerializer. As I need to update some tables from two sources I thought of using UUID as primary key for one entity.
I did a doctrine:mapping:import to generate entities in my Symfony project. Everything correct. I ended up with the following entity (only exposing the key field and generated getter for simplicity):
<?php
namespace Stardigita\TgaAPIBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TgaBookings
*
* #ORM\Table(name="tga_bookings", indexes={[...]})
* #ORM\Entity
*/
class TgaBookings
{
/**
* #var string
*
* #ORM\Column(name="book_cd_booking_UUID", type="blob", length=16, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $bookCdBookingUuid;
/**
* Get bookCdBookingUuid
*
* #return string
*/
public function getBookCdBookingUuid()
{
return $this->bookCdBookingUuid;
}
...
No setter was generated. I can still do it myself and I will, as I will need to know the key beforehand.
The data for this field is correctly stored in the table as a BINARY(16). When I recover the data calling the REST GET method, I get this:
[
{
"book_cd_booking_uuid": "Resource id #1244",
"book_cd_booking": 8,
....
My question is: how can I get the actual data from the field?
I suppose something has to be done in the field getter, but I tried some solutions without any success.
Thanks.
UPDATE:
I've managed to get the actual data logged, modifying the getBookCdBookingUuid method this way:
/**
* Get bookCdBookingUuid
*
* #return string
*/
public function getBookCdBookingUuid()
{
return bin2hex($this->bookCdBookingUuid);
}
and changed the type to "guid" in the property annotation:
/**
* #var string
*
* #ORM\Column(name="book_cd_booking_UUID", type="guid", length=16, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $bookCdBookingUuid;
I have represented the hex UUID correctly in the log before returning the results in the controller:
[2014-11-03 19:52:07] app.ERROR: 1046684e5f6711e4a09f00089bce936a [] []
But still getting an exception relating UTF invalid characters:
request.CRITICAL: Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters." at /var/www/tga_api/vendor/jms/serializer/src/JMS/Serializer/JsonSerializationVisitor.php line 36 {"exception":"[object] (RuntimeException: Your data could not be encoded because it contains invalid UTF8 characters. at /var/www/tga_api/vendor/jms/serializer/src/JMS/Serializer/JsonSerializationVisitor.php:36)"} []
Also I got no response from the service. A 500 error is returned.
Please, I need to solve this issue. Any ideas are welcome.
Thanks.
GeneratedValue
I notice you're using the annotation #ORM\GeneratedValue(strategy="IDENTITY") for the UUID property. IDENTITY means the database should/will use auto-increments, which shouldn't be done when using UUIDs. Please change it to #ORM\GeneratedValue(strategy="NONE") or remove it completely.
Conversion
The string form of a UUID (like 01234567-89ab-cdef-0123-456789abcdef) should be converted to binary when it's persisted in the database, and converted back when fetched from the database.
The easiest way to do this is to introduce a custom type. See here for an example.
Bugs
Doctrine (even master/2.5) has some issues with using UUIDs in associations. I'm attempting to fix these issues in PR #1178.
If you need UUIDs in associations and can't wait till it's fixed, then use regular integer ids and have the UUID is a separate column.

Doctrine: authorize NULL in a foreign composite key

I have the following entity:
/**
* SeriesAuthorRole
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Blog\Bundle\CoreBundle\Entity\SeriesAuthorRoleRepository")
*/
class SeriesAuthorRole extends AuthorRoleAbstract
{
/**
* #var Series
*
* #ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Series", inversedBy="authors")
* #ORM\JoinColumn(name="series", referencedColumnName="id", nullable=false)
* #ORM\Id
*/
private $series;
/**
* #var Author
*
* #ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Author")
* #ORM\JoinColumn(name="author", referencedColumnName="id", nullable=false)
* #ORM\Id
*/
protected $author;
/**
* #var Role
*
* #todo Must be nullable
*
* #ORM\ManyToOne(targetEntity="Blog\Bundle\CoreBundle\Entity\Role")
* #ORM\JoinColumn(name="role", referencedColumnName="id", nullable=true)
* #ORM\Id
*/
protected $role;
// ... Getters, setters
}
The idea behind it is quite simple: We have author, role and series entities. A series can have several authors with various roles. A same author can fulfill multiple roles in a series.
Sometimes, we don't know exactly what was the role of the author. In this case, the NULL value will be used for the role, the NULL value standing for "I don't know".
I was taught not to use NULL in foreign composite keys unless it has meaning. Well, it has meaning here, and I know that this could be implemented without Doctrine. However, for now, Symfony 2 throws that error:
Entity of type Blog\Bundle\CoreBundle\Entity\BandAuthorRole is missing an assigned ID for field 'role'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
500 Internal Server Error - ORMException
So how can I authorize NULL values in foreign composite keys ? Is it possible at all with Doctrine ?
Your #JoinColumn annotation is correct with referencing to http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-joincolumn
However,
Every entity with a composite key cannot use an id generator other
than “ASSIGNED”. That means the ID fields have to have their values
set before you call EntityManager#persist($entity).
http://docs.doctrine-project.org/en/2.0.x/tutorials/composite-primary-keys.html#general-considerations

using of unique constraint making the user unable to login in symfony2

I have used an unique constraint for the username in the registration form of the user.
User entity has following code
/*
* #UniqueEntity(fields="username",message="Username is already in use")
*/
class users
{
/**
* #var string
* #Assert\NotBlank(message="username should not be blank")
* #ORM\Column(name="username", type="string", length=40)
*
*/
private $username;
/**
* #var string
* #Assert\NotBlank(message="password should not be blank")
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
}
For registration every thing went fine with this entity when comes to login it is showing error username already in use. Can we keep the unique constraint within controller i.e within form.so that only for registration form uniqueness is applied.
Use validation groups:
http://symfony.com/doc/2.1/book/validation.html#validation-groups
(when you follow the link - you'll see very similar case: user and registration)
edit:
I assume that you have an "user_type" field in your user entity (for example possible values could be: "normal_user" and "affiliate"). If so, then you just need specify these two fields combination as a unique. Like this:
#UniqueEntity(fields={"username", "user_type"},message="Username is already in use") */

Resources