Many To One relationship in doctrine2 - php

I'm having trouble understanding doctrine and trying to make an entity. Would the following sql statement correspond with the following doctrine entity
create table comments (
id SERIAL PRIMARY KEY,
message VARCHAR,
parent_id INTEGER REFERENCES comments(id)
);
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="parent_id", type="integer")
* #ORM\OneToMany(targetEntity="Comment", mappedBy="id")
*/
private $parent_id;

You are mixing up the id's and the entity definitions a bit: with your example the parent_id variable would contain the parent comment entity instead of the id (that the variable name implies). Also your association is the wrong way around - it should be ManyToOne when defining the parent entity (many child comments for one parent comment).
Basically you can follow the example case in doctrine association mappins (section One-To-Many, Self-referencing) - there is also the entity relationship defined from parent comment to the children as an arrayCollection. In case you don't need the children connection you can just remove the related variable & inversedBy definition from the parent variable annotation.
If the referenced example is not clear enough I can post full code as well (as I happen to have precisely the same already done for comment entity)

The parent (which is another object than the initialized child) can have multiple 'childs', so the relationship should be a ManyToOne relationship.
Also take a look at the solution here: https://stackoverflow.com/a/24002956/1794894

Related

Nested composite foreign keys as ID in Doctrine

We are developing an online store in Symfony 5 and Doctrine 2 where multiple customers (called participants in this case) can participate in the same order item and share the cost. The following simplified class diagram demonstrates the domain model:
The pure object model works fine in unit tests, but you obviously need to persist the data to a database, which is why we need to introduce IDs.
Order, Product and Participant are entities with their own ID. In an ideal world, OrderItem and OrderItemParticipation would not need their own ID but be identified by the related entities they belong to, meaning their ID would be a composite foreign key.
So, an OrderItem would by identified by the composite key of Order.id and Product.id, which is pretty much exactly the same as given in this example from the Doctrine 2 documentation: https://www.doctrine-project.org/projects/doctrine-orm/en/2.10/tutorials/composite-primary-keys.html#use-case-3-join-table-with-metadata.
Since OrderItemParticipation relates to OrderItem, which uses a composite key itself, it would need to use a nested composite key consisting of Order.id, Product.id and Participant.id.
Unfortunately, Doctrine 2 doesn't seem to be able to work with nested composite keys as ID. I get this error
Column name id referenced for relation from
App\Entity\OrderItemParticipation towards App\Entity\OrderItem does
not exist.
when I try to generate a migration with the following mapping:
/** #ORM\Entity */
class OrderItem {
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity=Order::class, inversedBy="items")
*/
private Order $order;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity=Product::class)
*/
private Product $product;
// ...
}
/** #ORM\Entity */
class OrderItemParticipation {
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity=OrderItem::class, inversedBy="participations")
*/
private OrderItem $orderItem;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity=Participant::class)
*/
private Participant $participant;
// ...
}
So it seems that Doctrine is fine with my ID mapping in OrderItem, but it struggles when it gets to OrderItemParticipation. Is there a way to make Doctrine work with the given domain model? Is it maybe just an issue with the auto-generation of the migration, so if I had already manually set up the database, Doctrine might work with the given mapping? Or is the nested composite key ID approach too complicated for Doctrine?

How to make Doctrine PostgreSQL Foreign Key constrain DEFERRABLE

Using Doctrine2 and PostgreSQL I need to create foreign key constrains DEFERRABLE and INITIALLY DEFERRED
Found options "deferrable" and "deferred" In Doctrine/DBAL/Platforms/PostgreSqlPlatform.php, but have no idea where to use it inside Entity annotations
<?php
/**
* Class User
*
* #ORM\Table(name="jira_issues_changelogs")
* #ORM\Entity
* #package JiraBundle\Entity\Issue
*/
class Changelog
{
/**
* #var string
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="\JiraBundle\Entity\Issue", inversedBy="changelog")
* #ORM\JoinColumn(name="issue", referencedColumnName="id")
Need this column foreign key to be DEFERRABLE INITIALLY DEFERRED
*/
protected $issue;
I hit this same problem with an app I was working on, and came to the conclusion that the DEFERRABLE support in Doctrine DBAL isn't exposed to Doctrine ORM.
The crux of the problem is that in the ORM's SchemaTool the gatherRelationJoinColumns() method doesn't discover any $fkOptions except for onDelete. In order to support adding 'deferrable' there would need to be extended syntax in the ORM mapping layer for it.
In my case it was easier to just patch SchemaTool to add it than coordinate with upstream to add this properly, as there are very few references to people wanting to use advanced FK options on Google.
I thought I'd dump an answer here to avoid other people having to trace the issue themselves...
If someone wants to file a Doctrine ORM issue about it, be my guest!

How do I model my ER diagram when Doctrine won't let me associate composite primary key with another entity's foreign key?

I am trying to model the ManyToOne relations between
product_pricename and category_pricename
price_historyand product_pricename, as in the diagram below:
How?
Where I'm at
I note that this ER Diagram contains a composite foreign key,
I am talking about table product_pricename with key of (category_pricename_category_id, category_pricename_pricename_id)
which is part of another entity's primary key
I am talking about category_pricename with PRIMARY KEY of (category_id, pricename_id)
Which is totally okay by MySQL. But when I try to model this in Doctrine I get an error:
[Doctrine\ORM\Mapping\MappingException]
It is not possible to map entity 'CategoryPricename' with a composite
primary key as part of the primary key of another entity
'ProductPricename#categoryPricename'.
I so far have not visualized a proper way to do this in Doctrine.
I'm thinking I could introduce a surrogate PRIMARY KEY to entities product_pricename and category_pricename and re-model my tables. But would that be a way to do it?
Relevant Code
class CategoryPricename
{
/**
* #Id #ManyToOne(targetEntity="Category")
* #JoinColumn(name="category_id", referencedColumnName="id", nullable=false)
*
* #var Category
*/
private $category;
/**
* #Id #ManyToOne(targetEntity="Pricename")
* #JoinColumn(name="pricename_id", referencedColumnName="id", nullable=false)
*
* #var Pricename
*/
private $pricename;
}
class ProductPricename
{
/**
* #Id #ManyToOne(targetEntity="Product")
* #JoinColumn(name="product_id", referencedColumnName="id", nullable=false)
*
* #var Product
*/
private $product;
/**
* Note: I shortened the column names for my code
* by removing "category_pricename_" prefix for brevity
* as reflected in JoinColumn's name attributes
*
* #Id
* #ManyToOne(targetEntity="CategoryPricename")
* #JoinColumns({
* #JoinColumn(name="category_id", referencedColumnName="category_id", nullable=false),
* #JoinColumn(name="pricename_id", referencedColumnName="pricename_id", nullable=false)
* })
*
* #var CategoryPricename
*/
private $categoryPricename;
}
Natural vs Surrogate keys
It seems like with Doctrine I have to use surrogate keys in my tables to make my design work with Doctrine's limitations.
OR
I could go with mysqli and use natural keys (as in some tables of the ER Diagram now)
Part of me goes... which route do I go, surrogate (Doctrine) or natural (mysqli)
Modeling of more complex relations in Doctrine requires:
Model all relations as an entity. Have each such relation entity have a surrogate id primary key.
Instead of ManyToMany relation use ManyToOne for each side.
For the above to work, you may need change the structure of your tables to where you have no composite primary keys. That is due to Doctrine does allowing composite primary keys to be associated with foreign ids. It is a limitation. To work with this limitation means having more surrogate keys and less natural keys, which means having more table joins for i.e. querying price_history.
Alternative way is to use mysqli or PDO.
Alternative way is to not use Doctrine. Set up your tables however you need, and use mysqli or PDO. I chose to go this route because for my design I wanted to use full power of ER Design and DBMS and not have to deal with a lot of table joins.

How can I create a relation between entities twice

I am trying to create some sort of Inventory:
(The following Code is obviously not complete)
class User
{
/**
* #ORM\ManyToMany(targetEntity="Item", fetch="EAGER")
* #ORM\JoinTable(name="character_inventory_mm",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="item_id", referencedColumnName="id")}
* )
*/
private $inventory;
//etc
}
My Problem is that a User can have the same Item twice or even more often.
Is there a way to tell Doctrine not to create unique keys on those Relations or do I have to create some sort of mapping entity?
Something like:
* #ORM\ManyToMany(targetEntity="Item", fetch="EAGER", indexBy="NULL")
I have looked up doctrines joinTable and joinColumns and ManytoMany Documentation but I did not find a way to "fix" my Issue.
Thanks
That would need an unique key to differentiate multiple items connected to the same user.
Just create UserItems entity with a primary key and correspoding OneToMany and ManyToOne relations.

Doctrine - Custom form field based on query

I have 2 linked entities: User and Acess. I want my doctrine User entity to have a field that informs me if the user has acesses or not.
I can't do a simple OneToMany relationship between the two tables, because there is thousands of acesses and it would be too costly to get thousands of records from the database once I only need to know if there is any.
What I would want is a field linked to a native query like:
select * from accesses where user = <whatever> limit 1
More specifically, something like:
/**
* USer
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User {
/**
* #ORM\Column(name="user_id", type="bigint", nullable=false)
* #ORM\Id
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=300, nullable=false)
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\Query="select exists (select id_acesses from accesses where user = "$id" limit 1)"
*/
private $hasAcesses;
}
Is this possible ? is there another way to do this ?
Edit:
based on #Otanaught answer below, I have done some tests:
Using a OneToMany relation with EXTRA_LAZY fetch:
user-getAccesses()->isEmpty() selected the whole collection
user-getAccesses()->count() used count(*) in the database which took 243ms to return
for comparasion my query above who did what I want took 12ms in average with peeks of 2ms or even 1ms.
Maybe the good folks at doctrine could implement this at isEmpty for extra lazy queries ?
Thanx #Otanaught
Doctrine does not provide an annotation that allows you to specify a query for a property of an entity (Annotation reference). You could create a custom method in your repository to implement the check. Did you measure how costly the relation would be? With correct relations and indexes this should be a none issue, because doctrine lazy loads the relation? Check the doctrine documentation about extra lazy collections.

Categories