I have an issue with the following one-to-many unidirectional relation between UserSociable and Credential (I have simplified the code a little bit).
UserSociable entity is the owner of the relation:
/**
* Class UserSociable
* #ORM\Entity(repositoryClass="Repository\UserSociableRepository")
* #ORM\Table(name="userSociable")
* #DiscriminatorEntry(value="userSociable")
*/
class UserSociable
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Credential")
* #ORM\JoinTable (
* joinColumns={#ORM\JoinColumn(name="entity_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="credential_id", referencedColumnName="id", unique=true)}
* )
*/
private $credentials;
}
Credential entity is the inverse side:
/**
* #ORM\Entity(repositoryClass="Repository\CredentialRepository")
* #ORM\Table(name="credentials")
*/
class Credential
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
}
These creates three tables in DB:
userSociable
credentials
usersociable_credential
Once the DB is populated, I have the following issue: when I delete a userSociable, Doctrine automatically also removes the corresponding rows in the join table usersociable_credential.
I was expecting an exception to raise since the PK is referenced as FK in usersociable_credential table. This is the expected behaviour since I never used an annotation like onDelete="CASCADE" in the join column annotation.
The thing is I want to force to delete all the user's Credentials before to being able to delete an UserSociable.
I have looked at MySQL log file and found the following queries:
151106 12:16:24 113 Query START TRANSACTION
113 Query DELETE FROM usersociable_credential WHERE entity_id = '1'
113 Query DELETE FROM ku_user WHERE id = '1'
113 Query commit
113 Quit
112 Quit
How can I avoid the query DELETE FROM usersociable_credential WHERE entity_id = '1' to be created and executed by Doctrine???
Thanks in advance.
Related
Given this code, Doctrine launchs as many querys as rows I have in table2
$qb = $this->getModelManager()->createQuery($er->getClassName(), 't1')->getQueryBuilder();
$qb->select('t1, t2, t3')
->innerJoin('table1.table2', 't2');
->innerJoin('table2.table3', 't3')
->where('t3.id = :foo')
->setParameter('foo', $foo);
each query is like this one:
SELECT t0.id AS id_1,
t0.name AS name_2,
t0.slug AS slug_3,
t0.description AS description_4,
t0.visible AS visible_5
FROM table2 t0
WHERE t0.id = ?
and those are the entities:
TABLE1: The main entity, witch is related to table 2 by manyToOne if I make the innerJoin with table 2, Doctrine act as expected (1 query)
/**
* #ORM\Entity(repositoryClass = "Table1Repo")
* #ORM\Table(name="table1")
*/
class table1 extends BaseTable1 implements table1Interface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
* #Gedmo\Versioned
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="table2", inversedBy="tables1")
* #ORM\JoinColumn(name="table2_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $table2;
}
TABLE2, related with table one by OneToMany, and with table 3 by ManyToMany.
/**
* #ORM\Entity(repositoryClass="table2Repository")
* #ORM\Table(name="table2")
*/
class table2 extends Basetable2
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="table3", inversedBy="table2s")
* #ORM\JoinTable(name="table3_table2")
*/
protected $table3;
/**
* #ORM\OneToMany(targetEntity="table1", mappedBy="table2")
* #Accessor(getter="getTables1")
*/
protected $tables1;
}
TABLE3: oly related with table 2 by a ManyToMany relation. When I make the innerJoin with table 2, Doctrine still acts as expected, making only one query
/**
* #ORM\Entity(repositoryClass = "table3Repo")
* #ORM\Table(name="table3")
* #Gedmo\Loggable
*/
class table3 extends Basetable3
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="table2", mappedBy="tables3")
* #ORM\JoinTable(name="table3_table2")
*/
protected $tables2;
}
So, as I add both innerJoins to the query Builder, Doctrine makes only one query, but is when I add the WHERE clause, when Doctrine makes the 279 querys, one per row in table2, witch is related with table1 by oneToMany and with table3 by ManyToMany.
Other relevant point is that the querybuilder is beeing executed under SonataAdmin query_builder fiel option.
I can't find why I'm getting this behaviour, any clue?
When you run a query, you always need to have a root entity which joins to others. In your case, that is table1. After fetching, based on query and entity metadata, Doctrine will attempt to create an object for each instance of root, but unless told otherwise, it will stop there. In fact, for each sub-objects (e.g. table2), it will create dummy "proxy" objects which are barely shallow representations, and are to be resolved from DB whenever to try to dereference them. The process of converting DB results to objects is known as object hydration.
In order to do perform hydration of sub-objects, you need to "select" sub-entity as well:
$qb->select('t1', 't2', 't3')
->innerJoin('t1.table2', 't2');
->innerJoin('t2.table3', 't3')
->where('t3.id = :foo')
->setParameter('foo', $foo);
Pay attention not to go crazy with fetching everything, as it takes longer and consumes reasonably more RAM. Fine-tune your query, until you reach what you want (logic and performance-wise).
Hope this helps...
I was hoping this be a straight forward process but it seems Doctrine doesn't really like the idea of linking entities through their IDs.
All I intended to do was normalising a table by shipping some fields from it to a new table and instead of adding a new reference field to the original table to hold the ID of the new corresponding record in the, make sure the new record in the child table will have identical ID to its parent row.
Here is an example of what I have:
A User entity, with annotated field $user to reference column ID in the UserDetail entity to itself's ID
/**
* #ORM\Table(name="user", options={"collate"="utf8_general_ci", "charset"="utf8", "engine"="InnoDB"})
* #ORM\Entity
*/
class User extends Entity
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id
/**
* #ORM\OneToOne(targetEntity="UserDetail", cascade={"persist"})
* #ORM\JoinColumn(name="id", referencedColumnName="id", nullable=true)
*/
private $userDetail;
...
}
and here is the UserDetail with its ID's #GeneratedValue removed
/**
* #ORM\Table(name="user_detail", options={"collate"="utf8_general_ci", "charset"="utf8", "engine"="InnoDB"})
* #ORM\Entity
*/
class UserDetail extends Entity
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
*/
private $id;
...
}
At this point what my expectation was to be able to do something like:
$user = new User();
$userDetail = new UserDetail();
$user->setUserDetail($userDetail)
$entityManager->persist($user);
$entityManager->flush();
And get two records persisted to the user and user_detail tables with identical IDs, but the reality is, not having any strategy defined for the UserDetail's identifier, doctrine will complaint about the missing ID, Entity of type UserDetail is missing an assigned ID for field 'id'.
Of course it is possible to do the job manually and in more than one call
$user = new User();
$entityManager->persist($user);
$entityManager->flush();
$userDetail = new UserDetail();
$userDetail->setId($user->getId)
$user->setUserDetail($userDetail)
$entityManager->persist($user);
$entityManager->flush();
But I'm still hoping there is a correct configuration (annotation) that can help me to avoid such extra steps and leave handling of a one-to-one relationship through the entity's IDs to Doctrine.
This is untested but I think the following might work, according to the docs (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html):
/**
* #ORM\Table(name="user_detail", options={"collate"="utf8_general_ci", "charset"="utf8", "engine"="InnoDB"})
* #ORM\Entity
*/
class UserDetail extends Entity
{
/**
* #var integer
*
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="id", referencedColumnName="id")
* #ORM\Id
*/
private $user;
...
}
Let's say I have a simple entity EstablishmentEntity, with a ManyToOne relationship on $employee that looks like this :
namespace Msm\CeopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Msm\CeopBundle\Entity\Establishment;
/**
* Establishment
*
* #ORM\Table(name="establishment")
* #ORM\Entity()
*/
class School
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="Professionnal", cascade={"persist"})
* #ORM\JoinColumn(name="teacher_id", referencedColumnName="id", nullable=true)
*/
private $employee;
My problem : that entity is used for different kinds of establishments and has a lot more useful attributes in my code (I kept it simple for my question). One kind of establishement won't have any employees. Is it possible to tell Doctrine/symfony NOT to cascade persist the employee in that perticular case after class instanciation for example ?
So far it automatically persists an empty employee entity when creating an establishment, which is ok for most establishments but not all...
Class Comment
/**
* #var \Caerus\AppBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="User" , inversedBy="comment")
*
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
*
*/
protected $user;
Class User
/**
* #var mixed
*
* #ORM\OneToMany(targetEntity="Comment", mappedBy="user")
*/
protected $comment;
Basically quite simple. I need the comments class to have a user_id field which is a direct copy of the original user_id field from the users class.
The error is as following:
[Doctrine\ORM\ORMException] ManyToOne Column name id referenced for relation from Comment towards User does not exist
Why exactly is it still saying doesn't exist and how do I solve that ?
Referenced Column name should be the "id" property of the User class.
/**
* #var \Caerus\AppBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="User" , inversedBy="comment")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*
*/
protected $user;
P.S.
I would also name the OneToMany property "comments" as it holds many Comment objects.
"#var \Caerus\AppBundle\Entity\Users" should be ...\User as your class is called User
Running php bin/console doctrine:schema:validate will give you more insight into which entity classes and columns are involved in the error condition.
Also you can use this code:
/**
* #var \Caerus\AppBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="User" , inversedBy="comment")
*
* #ORM\JoinColumn(nullable=true , referencedColumnName="variable_id_of_comment")
*/
protected $user;
I have the following property in my User entity to track followers and following. Basically a user can follow other user as well. I have a join column called app_user_follow_user, however I also wanted to add a timestamp of whenever someone follows another user, when did it happen. How can I specify a created timestamp via this ORM?
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="following")
*/
protected $followers;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="followers")
* #ORM\JoinTable(name="app_user_follow_user",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="follow_user_id", referencedColumnName="id")}
* )
*/
protected $following;
Doctrine ManyToMany relationships are used when your join table has two columns. If you need to add another column you have to convert the relationship to OneToMany on both sides and ManyToOne on the joined entity.
This is entirely untested but it will hopefully give you the gist.
User Entity
/**
* #ORM\OneToMany(targetEntity="AppUserFollowUser", mappedBy="appUser")
*/
protected $followers;
/**
* #ORM\OneToMany(targetEntity="AppUserFollowUser", mappedBy="followUser")
*/
protected $following;
AppUserFollowUser Entity
/**
* #ORM\Table(name = "app_user_follow_user")
*/
class AppUserFollowUser
{
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="User", inversedBy="followers")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $appUser;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="User", inversedBy="following")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="follow_user_id", referencedColumnName="id")
* })
*/
private $followUser;
/**
* #ORM\Column(name="created_date", type="datetime", nullable=false)
*/
private $createdDate;
}
I think that you will have to create a link entity manually (entiy1 onetomany linkEntity manytoone entity2.
Because, the usual link entity are automated and should be as simple and (data less) as possible, so doctrine can take all the controle over it,
imagine you need to get the timestamp, how can you do it on an (none hard coded) entity, you will need a getter, and the annotations are not supposed to contains code.