How to update referenced key id to null in one to one doctrine - zend-framework

I am running in this issue. Whenever I delete a company entity, the contact entity which has company's id as reference key throws an error.
Company for IDs ID(29) was not found
I have this:
Contacts Table
ID, Name, Company_ID
Companies Table
ID, Name
And I have these relationships in their entities.
Contact.php
/**
* #ORM\OneToOne(targetEntity="Company", cascade={"persist"})
* #ORM\JoinColumn(name="Company_ID", referencedColumnName="ID")
*/
private $company;
Company.php
/**
* #ORM\OneToMany(targetEntity="Contact", mappedBy="company")
* #ORM\JoinColumn(name="ID", referencedColumnName="Company_ID")
*/
private $contacts;
I'm fairly new to doctrine. But when I delete a company of ID 1 then all the contacts with Company_ID = 1 should become null. Is this something that doctrine could handle or I MUST write manual code for it.

Related

detach single belongsToMany relationship

I need to detach a single belongs to many relationship however I can't figure it out. Below is how I have got the belongsToMany relationship setup:
WebsiteController
/** #var User $user */
$user = \Auth::user();
$favorites = $user->favoriteWebsites;
User
/**
* #return BelongsToMany
*/
public function favoriteWebsites(): BelongsToMany
{
return $this->belongsToMany(Website::class, 'planner_favorite_websites');
}
When a user clicks a button I will have access to the website ID associated with the pivot table. Tables are setup like follows:
websites
id, name, code
users
id, fname, lname
planner_favorite_websites
id, user_id, website_id
How can I use the website ID to detach just that single website from the current user logged in. So I will have the Website ID and User ID.
Obviously I could do a simple where(['website_id' => 0, 'user_id' => 0]) but this doesn't seem the correct way to use relationships.

Finding an inherited entity over a jointable with NamedQuery

How can I use a NamedQuery to find an entity over a jointable?
I have an abstract parent class/entity with #Inheritance(strategy=InheritanceType.JOINED) and two subclasses/subentities.
Hence, in the database I have a parent table (sdrs) and two subtables (xSdrs and ySdrs).
There is another table reservations which shall have a Many-to-Many relationship to table sdrs. That's why I created a jointable between reservations and sdrs.
I intend to have a NamedQuery in the parent entity Sdr to be able to find the key for a record/entity of XSdr or YSdr respectively over the jointable.
In class Sdr I have:
#NamedQuery(name="Sdr.findBySdrId", query="SELECT s FROM Sdr s "
+ "INNER JOIN s.reservations res WHERE res.sdrs = :transactionId")
and
#ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#JoinTable(name="sdrs_has_reservations",
joinColumns = {
#JoinColumn(name="sdrs_id", referencedColumnName="sdrId", nullable=false)
}, inverseJoinColumns={
#JoinColumn(name="reservations_id", referencedColumnName="reservationId", nullable=false)
})
private List<Reservation<T>> reservations;
But, of course, this sets the transactionId to reservationId which consequentially fails.
On the inverse side I have:
#ManyToMany(mappedBy="reservations", fetch=FetchType.EAGER)
private List<Sdr<T>> sdrs;
So, how do I have to implement the named query in class/entity Sdr to be able to get the proper Sdr (and its related reservations) with an Sdr ID to be set as query parameter?
SELECT sdr FROM Reservation r JOIN r.sdrs sdr WHERE sdr.id=:id

Not able to define column type in JoinColumn for a foreign key reference in Symfony2/Doctrine

This seems like it should be an easy issue but I can't seem to get it solved.
I have two Entities, Person and Flag. Flag has a ManyToOne relationship to Person. Where I'm running into an issue is that Person's id field is a bigint, not a type int.
So, with syntax like this on the ManyToOne field on the Flag entity:
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="flags")
* #ORM\JoinColumn(name="personId", referencedColumnName="id")
*/
protected $person;
I get a Foreign Key error, something along the lines of
An exception occurred while executing 'ALTER TABLE flags ADD CONSTRAINT FK_B0541BAA20C4B1C FOREIGN KEY
I believe I've exhausted all other possibilities of this error besides it being generated because the personId field is an integer and the person's ID field is a bigint. These foreign key relationships have been working fine among other entities in this bundle, its only the Person and its bigint primary key that is causing issues.
I can't add type="bigint" to JoinColumn without getting an error like:
The annotation #ORM\JoinColumn declared on property Acme\AcmeBundle\Entity\PersonFlag::$person does not have a pro
perty named "type"
And, if I add Column annotation in order to declare the type, it just ignores the JoinColumn, as shown below:
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="flags")
* #ORM\JoinColumn(name="personId", referencedColumnName="id")
* #ORM\Column(type="bigint")
*/
protected $person;
This doesn't generate any errors, but it creates a column named "person" that has no foreign keys.
So, what am I missing, how can I go about adding this ManyToOne relationship to an entity that has a bigint as it's primary key?
Here is the annotation for the Person entity's ID field:
/**
* #ORM\Id
* #ORM\Column(type="bigint")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
TY!
In relationships between entities I think you could avoid the column type, because the foreign keys should be already mapped in the model (for example, the IDs). Try this:
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="flags")
* #ORM\JoinColumn(name="personId", referencedColumnName="id")
*/
protected $person;
Then, in your person model you should have something like this:
/**
* #OneToMany(targetEntity="Flag", mappedBy="person")
*/
protected $flags;

doctrine proxy OneToOne entity has the identity name set to [] but value is correct

Hi i'm having a slight issue with a OneToOne relationship which when runs the below:-
$userToView = $this->view->entityManager->getRepository("Ajfit\Entity\User")
->findOneByName($userName);
This populates as intended but the a relational field called engineerFk, which is a proxy entity has the identifier field set to [] but with the value set correctly, see below:-
My User entity is this:-
class User extends PersistentObject
{
/**
* #var integer $pk
*
* #ORM\Column(name="pk", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $pk;
/**
* #var integer $engineerFk
* #ORM\OneToOne(targetEntity="Ajfit\Entity\Engineer")
* #ORM\JoinColumn(name="pk", referencedColumnName="user_fk")
*/
protected $engineerFk;
}
My engineer entity setup like this:-
class Engineer extends PersistentObject
{
/**
* #var integer $pk
*
* #ORM\Column(name="pk", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
}
protected $pk;
And my sql in the database is this:-
/*user table*/
CREATE TABLE `user` (
`pk` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`pk`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
/*engineer table */
CREATE TABLE `engineer` (
`pk` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_fk` int(10) unsigned NOT NULL,
PRIMARY KEY (`pk`),
KEY `engineer_user_fk` (`user_fk`),
CONSTRAINT `engineer_user_fk` FOREIGN KEY (`user_fk`) REFERENCES `user` (`pk`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
Any help reagrding this problem would be much apprieciated.
Thanks
Andrew
I think that you're defining the owning side of the relationship on the wrong entity. It should be defined on the entity that owns the foreign key.
I'm not comfortable with annotations, so I'll use YAML to describe the association.
So, for the Engineer entity, you should have something like:
oneToOne:
user:
targetEntity: User
inversedBy: engineer
joinColumn:
name: user_fk
referencedColumnName: pk
Then, for the User entity, the config should be like this:
oneToOne:
engineer:
targetEntity: Engineer
mappedBy: user
Read this for details.
Also, with such association mapping, the Doctrine 2 console tool will generate slightly different entity classes.
Most likelly, it's got to do with lazy loading. Your proxy object will not be loaded until you start using it.

Symfony2 UniqueEntity validation constraint as concatenation?

In my Tag entity i need to avoid creating a tag with the same name along all tags created by a given user. There is a many-to-one relation with User entity, named user.
I'm enforcing this constraint either in database (using uniqueConstraints) and in form validation with UniqueEntity. But i can't understand this sentence in Symfony2 documentation about this constraint:
This required option is the field (or list of fields) on which this
entity should be unique. For example, you could specify that both the
email and name fields in the User example above should be unique.
But i need that name and user are unique as a whole. Is this possible and how? Here is an example of not working one: both name and user are checked for uniqueness as singular fields.
/**
* #ORM\Entity(repositoryClass="Acme\HelloBundle\Repository\TagRepository")
* #ORM\Table(
* name="tag",
* uniqueConstraints={
* #ORM\UniqueConstraint(columns={"name", "user_id"}),
* })
* #UniqueEntity(fields={"name", "user"})
*/
class Tag implements TenantableEntityInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=31)
* #Assert\NotBlank
* #Assert\MaxLength(limit="31")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="tags")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
}
EDIT: with the definition above the form validates but i get the:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'name-1' for key 'UNIQ_389B7835E237E06A76ED395'.
Creating two tags with the same name and the same user.
If you want the combination of both name and user be unique, then use:
#UniqueEntity(fields={"name", "user"})
If you want them be unique separately, use this:
#UniqueEntity(fields="name")
#UniqueEntity(fields="user")
The same applies for unique constraints on the table.
Just note:
For yaml use:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: username
groups: [SomeYourGroup]
Or for annotation:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
#UniqueEntity(fields={"username"}, groups={"SomeYourGroup"})
In documentation http://symfony.com/doc/current/reference/constraints/UniqueEntity.html
groups not available!!!