I have created two entities of existing database tables, these tables use the doctrine conventions for table relationships, I need to relate the tables to be able to work, the entities work by consulting data, but not between them.
Table name "Articulos"
class Articulos
{
/**
* #ORM\Id()
* #ORM\Column(type="integer")
*/
private $ID_Articulo;
/**
* #ORM\Column(name="ID_Clasificacion_Articulo", type="integer")
* #ORM\ManyToOne(targetEntity="ClasificacionesArticulos")
*/
private $ID_Clasificacion_Articulo;
.......
Table name "ClasificacionesArticulos"
class ClasificacionesArticulos
{
/**
* #ORM\Column(name="ID_Clasificacion_Articulo", type="integer")
* #ORM\Id()
* #ORM\OneToMany(targetEntity="Articulos", mappedBy="ID_Clasificacion_Articulo")
*/
private $ID_Clasificacion_Articulo;
/**
* #ORM\Column(type="string", length=150)
*/
private $Codigo;
/**
* #ORM\Column(type="string", length=150)
*/
private $Nombre;
.........
When I consult any of the entities, returns result without children of relationships. I suppose it's because of the names of the fields id does not use the name strategies, but I can not change them in the database, I have to adapt to it by requirements.
If someone has an idea, I thank you very much
This can be accomplished by implementing custom Doctrine naming strategy. In Symfony entity, use camelCase to avoid any problems with naming. But, if you need specific table names follow the guide
You have to implement NamingStrategy class:
class CustomNamingStrategy implements NamingStrategy
{
}
register it as a service by adding following to the end of the the config/services.yaml :
app.naming_strategy.custom:
class: App\Service\CustomNamingStrategy
autowire: true
Then specify naming strategy by editing config/packages/doctrine.yaml as follows:
naming_strategy: app.naming_strategy.custom
I believe you are looking for propertyToColumnName method, as Doctrine says
If you have database naming standards, like all table names should be
prefixed by the application prefix, all column names should be lower
case, you can easily achieve such standards by implementing a naming
strategy.
Related
I have a table that has composite primary key: id + est_date. And it has an entity:
class Parent
{
/**
* #ORM\Id
*/
private $id;
/**
* #ORM\Id
*/
private int $estDate;
...
}
Now I need to create a related table and its entity.
class Child
{
...
/**
* don't know what to write here
*/
private $parentId;
/**
* don't know what to write here
*/
private int $parentEstDate;
...
}
How to discribe relation ManyToOne (many "Child" entities may relate to 1 "Parent")? And the second issue is - "estDate" of the "Parent" may change. How to specify cascade update in "Child"?
Please don't write that doctrine doesn't recomment to use composite keys. I know that.
on the child-entity you would refer to the parent entity the same way as with single columns, essentially. Starting with
annotation version:
/**
* #ORM\ManyToOne(targetEntity=Parent::class)
*/
private ?Parent $parent;
since the child is the owning side, you have to provide join columns, as you have noticed. There is a badly documented annotation JoinColumns that allows to define multiple join columns. (Note for those using the attribute syntax instead: you should be able to have multiple #[JoinColumn(...)], without the JoinColumns-Wrapper)
annotation version:
/**
* #ORM\ManyToOne(targetEntity=Parent::class)
* #ORM\JoinColumns({
* #ORM\JoinColumn("parent_id", referencedColumnName="id"),
* #ORM\JoinColumn("parent_est_date", referencedColumnName="est_date")
* })
*/
private ?Parent $parent;
If you want to add the inverse side as well, you always reference the object property, not the columns when using mappedBy/inversedBy.
Generally with doctrine-orm: Your class/object should not care about columns, only about php stuff, doctrine should handle the rest. The annotations tell doctrine, how this converts to columns. So not every column will get its own property in this case.
So, I need a validation for a reservation for a sports club.
A reservation has a start and an end datetime and you can reservate for 1 or more tables.
So the Entity looks like
class Reservation
{
use TimestampAble;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="reservations")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Table", inversedBy="reservations")
*/
private $tables;
/**
* #ORM\Column(type="datetime")
*/
private $start;
/**
* #ORM\Column(type="datetime")
*/
private $end;
...
}
(Don't worry about the entity "Table" - the db table for it is named "snooker_table" ;))
Now I need to validate, that in the requested time range with the requested tables no other reservation already exist.
And this gives me headaches...
I know I can make it "manually" in the Controller Actions create / update. But I'm also using Symfonys Easy-Admin, so I need to put the code there as well.
I thought about putting the validation as an annotation directly into the entity. But I don't know where... If I put it on "$tables" I just get an ArrayCollection without the needed start and end datetimes. And it's also not an unique entity (as I need to go on a range of datetimes and so on).
So: any ideas how to achieve this in the entity directly? or at least in the form type (and for easy admin i care later)?
Thx in advance.
Ok, I'm going to do it in this way: Symfony 2 UniqueEntity repositoryMethod fails on Update Entity
Creating a repository method (not a constraint) for validation and use it for the UniqueEntity constraint on the whole entity itself. Feels a little bit dirty but ok...
Hope this works in easy admin as well.
I have been doing some research on this topic but so far I couldn't find anything helpful for my scenario.
In a brief: I have two tables Quote (table name: quote) and QuoteArchive (table name: quote_archive). Both share exactly the same columns and types. As far as I have read this turn into a Doctrine MappedSuper Class ex: MappedSuperclassQuote.
After that Quote and QuoteArchive entities will extend from the MappedSuperclassQuote and both will share exactly the same structure.
Quote has a custom Repository with some functions. QuoteArchive needs exactly the same Repository functions as in Quote with the only difference being the table name and the PK.
I have two doubts in this scenario:
How to extend Doctrine entities when the PK (#Id) is different in the child classes?
How to extend or share the same repository between entities when the only change is the table name.
For get a better idea this is how my current entities looks like:
/**
* #ORM\Entity
* #ORM\Table(name="quote")
* #ORM\Entity(repositoryClass="QuoteBundle\Entity\Repository\QuoteRepository")
*/
class Quote
{
/**
* #ORM\Id
* #ORM\Column(type="integer",unique=true,nullable=false)
* #ORM\GeneratedValue
*/
private $quoteId;
// ...
}
/**
* #ORM\Entity
* #ORM\Table(name="quote_archive")
* #ORM\Entity(repositoryClass="QuoteBundle\Entity\Repository\QuoteArchiveRepository")
*/
class QuoteArchive
{
/**
* #ORM\Id
* #ORM\Column(type="integer",unique=true,nullable=false)
*/
private $archiveId;
// ...
}
Last but not least:
class QuoteRepository extends EntityRepository
{
public function getCurrentQuoteId(int $OrigQuoteId)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
return $qb->select('q')
->from('QuoteBundle:Quote')
->where('q.origQuoteId =:origQuoteId')
->setParameter('origQuoteId', $OrigQuoteId)
->andWhere('q.quoteType =:quoteType')
->setParameter('quoteType', 'current')
->getQuery()
->getResult();
}
}
What is the problem here? I need to repeat the same exact function in QuoteArchiveRepository and change the table from quote to quote_archive and it's exactly what I am trying to avoid if possible.
Can any give me some ideas? Code example would be great :)
References:
Can we extend entities in Doctrine?
Doctrine: extending entity class
Doctrine How to extend custom repository and call the extended repository from doctrine entity manager
I think you're mistaking doing a MappedSuperclassQuote entity.
You have to inherit the Archive from the Quote.
Example : you have your Quote entity
The definition should be something like :
/**
* #ORM\Table(name="app_quote")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="quote_type", fieldName="quoteType", type="string")
* #ORM\DiscriminatorMap({
* "quote":"YourBundle\Entity\Quote",
* "quote_archive":"YourBundle\Entity\QuoteArchive"
* })
* #Gedmo\Loggable
* #ORM\Entity(repositoryClass="YourBundle\Repository\QuoteRepository")
*/
Why a JOINED inheritance ? Cause you want two separate tables (what SINGLE_TABLE is not doing) and you don't have a really abstract class (cause Quote AND QuoteArchive means something for you)
After, your table QuoteArchive should extends the first one :
/**
* #ORM\Entity
* #ORM\Table(name="app_quote_archive")
*/
class QuoteArchive extends Quote
{
...
}
Your column quote_type in app_quote will help you to know if this is an archived quote or not.
It provides you all you want :
- QuoteArchive will have access to functions inside QuoteRepository
- Each table has separated ids
One thing could be annoying for you : if you want to set a quote has archived, it's not so easy to change an entity type for now in Doctrine. In that case, it's better for you to use single_table joining type. All the datas are stored in a same table in database, making type change easy but you keep two different entities.
I'm having trouble using entity inheritance in Symfony2. Here are my two classes:
use Doctrine\ORM\Mapping as ORM;
/**
* #Orm\MappedSuperclass
*/
class Object
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
/**
* #Orm\MappedSuperclass
*/
class Book extends Object
{
}
When I run php app/console doctrine:schema:create I get the following error:
[Doctrine\ORM\Mapping\MappingException]
Duplicate definition of column 'id' on entity 'Name\SiteBundle\Entity\Book' in a field or discriminator column mapping.
What may be causing this?
Thanks :)
Update:
You are right I missed this. Now I'm using single table inheritance with both classes being entities:
/**
* #Entity
* #InheritanceType("SINGLE_TABLE")
* #DiscriminatorColumn(name="discr", type="string")
* #DiscriminatorMap({"object" = "Object", "book" = "Book"})
*/
But I still get the same error message.
Actually I found yml files in Resources/config/doctrine/, which were defining my entities, instead of just using annotations.
I removed these files and it's working now.
Thanks for your help !
I had same issue even after adding definitions to yml file. I was trying to add weight & max weight to a class and was getting:
Duplicate definition of column 'weight_value' on entity 'Model\ClientSuppliedProduct' in a field or discriminator column mapping.
Then I realized it requires columnPrefix to be different for similar types of fields and adding following in yml solved it for me:
`maxWeight:`
`class: Model\Weight`
`columnPrefix: max_weight_`
I had the same problem and error message but for me it was the other way around as #user2090861 said.
I had to remove the (unused)
use Doctrine\ORM\Mapping as ORM;
from my entity files, cause my real mapping comes from the orm.xml files.
I hope I can help with my answer many other people, cause this exception drove me crazy the last two days!
I ran into this in a different context - in my case, I had set up an entity for single-table inheritence using #ORM\DiscriminatorColumn, but had included the column in my class definition as well:
/**
* #ORM\Entity(repositoryClass="App\Repository\DirectoryObjectRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="kind", type="string")
*/
class DirectoryObject {
// ...
/**
* #ORM\Column(type="string", length=255)
*/
private $kind;
}
Removing the #ORM\Column definition of kind fixed this issue, as Doctrine defines it for me.
Sometimes it's impossible to remove extra config files, because theay are located in third party bundle and auto_mapping is enabled.
In this case you should disable undesirable mappings in app/config.yml
doctrine:
orm:
entity_managers:
default:
mappings:
SonataMediaBundle: { mapping: false }
Any entity must contain at least one field.
You must add at least one field in Book Entity
Example
/**
* #Orm\MappedSuperclass
*/
class Book extends Object
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
I had the same error message but I had made a different mistake:
Class B had an ID and extended Class A which also had an ID (protected, not private). So I had to remove the ID from Class B.
I currently have a model structure as follows:
/**
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="related_type", type="string")
* #ORM\DiscriminatorMap({"type_one"="TypeOne", "type_two"="TypeTwo"})
*/
abstract class BaseEntity {
... (all the usual stuff, IDs, etc)
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="baseEntity")
*/
private $comments;
}
/**
* #ORM\Entity
*/
class TypeOne extends BaseEntity {
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $description;
}
/**
* #ORM\Entity
*/
class TypeTwo extends BaseEntity {
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $description;
}
/**
* #ORM\Entity
*/
class Comment {
... (all the usual stuff, IDs, etc)
/**
* #ORM\ManyToOne(targetEntity="BaseEntity", inversedBy="comments")
*/
private $baseEntity;
}
The idea here is to be able to tie a comment to any of the other tables. This all seems to be working ok so far (granted, I'm still exploring design options so there could be a better way to do this...), but the one thing I've noticed is that the subclasses have some common fields that I'd like to move into a common parent class. I don't want to move them up into the BaseEntity as there will be other objects that are children of BaseEntity, but that won't have those fields.
I've considered creating a MappedSuperclass parent class in the middle, like so:
/**
* #ORM\MappedSuperclass
*/
abstract class Common extends BaseEntity {
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $description;
}
/**
* #ORM\Entity
*/
class TypeOne extends Common {}
/**
* #ORM\Entity
*/
class TypeTwo extends Common {}
I figured this would work, but the doctrine database schema generator is complaining that I can't have a OneToMany mapping on a MappedSuperclass. I didn't expect this to be a problem as the OneToMany mapping is still between the root BaseEntity and the Comment table. Is there a different structure I should be using, or other way to make these fields common without adding them on the BaseEntity?
From the Docs:
A mapped superclass is an abstract or concrete class that provides
persistent entity state and mapping information for its subclasses,
but which is not itself an entity. Typically, the purpose of such a
mapped superclass is to define state and mapping information that is
common to multiple entity classes.
That said, how can you associate one entity with one that is not?
More from the docs:
A mapped superclass cannot be an entity, it is not query-able and
persistent relationships defined by a mapped superclass must be
unidirectional (with an owning side only). This means that One-To-Many
assocations are not possible on a mapped superclass at all.
Furthermore Many-To-Many associations are only possible if the mapped
superclass is only used in exactly one entity at the moment. For
further support of inheritance, the single or joined table inheritance
features have to be used.
Source: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html
Update
Because your MappedSuperClass extends BaseEntity it also inherits the BaseEntity's associations, as if it were its own. So you effectively DO have a OneToMany on a MappedSuperClass.
To get around it, well, you'd need to modify/extend doctrine to work the way you want.
As far as native functionality goes you have two options:
Class Table Inheritance
You Common class and the resulting DB representation would have the common fields and child classes will now only have the fields specific to themselves. Unfortunately this may be a misrepresentation of your data if you are simply trying to group common fields for the sake of grouping them.
Make Common an Entity
It appears that all a Mapped Super Class is is an Entity that isn't represented in the DB. So, make common a Entity instead. The downside is that you'll end up with a DB table, but you could just delete that.
I recommend that you take a second look at your data and ensure that you are only grouping fields if they are common in both name and purpose. For example, a ComputerBox, a ShoeBox, a Man, and a Woman may all have the "height" property but in that case I wouldn't suggest have a Common class with a "height" property that they all inherit from. Instead, I would have a Box with fields common to ComputerBox and ShoeBox and I'd have a Person with fields common to Man and Woman. In that situation Class Table Inheritance or single table if you prefer would work perfectly.
If your data follows that example go with Single Table or Class Table Inheritance. If not, I might advise not grouping the fields.