Doctrine 2 Mapping of 2 tables, error - php

Zend Framework 3, Doctrine 2. I created some mapping of 2 tables MySQL
/**
* #ORM\Entity
* #ORM\Table(name="object")
*/
class Object
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="..\Host", inversedBy="object")
* #ORM\JoinColumn(name="ip", referencedColumnName="IP")
*/
protected $host;
}
/**
* #ORM\Entity
* #ORM\Table(name="host")
*/
class Host
{
/**
* #ORM\Id
* #ORM\Column(name="IP")
*/
protected $ip;
/**
* #ORM\OneToOne(targetEntity="..\Object", mappedBy="host")
* #ORM\JoinColumn(name="IP", referencedColumnName="ip")
*/
protected $object;
}
I have this error:
Error "Missing value for primary key id on ..\Object".
Why? It seems to be done according to the example -> 5.3. One-To-One, Bidirectional from the site Doctrine

The parameters you pass to JoinColumn are incorrect. You can check the doc for JoinColumn here.
Try like this:
// For Object class:
// #ORM\JoinColumn(name="host_ip", referencedColumnName="ip")
// For Host class
// #ORM\JoinColumn(name="object_id", referencedColumnName="id")
In addition to this: mappedBy is not supported in OneToOne annotations. You can use targetEntity and inversedBy but not mappedBy.
On the other hand, making the ip your primary key seems wrong. You should have an auto-generated primary id for Host and use that to connect the entities. You can still set you ip field as unique, so you won't have duplicates. Plus you don't have any other fields, you can even just put the ip within Object class.
Also, I don't recommend using Object as your class name. It is too general.

Related

symfony2 - ManyToMany with duplicate rows

I currently have to Entities in my application:
Page
Block
A Page can have many Blocks, which are shared across many Pages, so it is quite obvious that the relation is a ManyToMany. However, I need to be able to add the same Block twice (or more) to the same Page. Doctrine creates the "page_block" join table automatically, but with page_id and block_id both as Primary Keys, therefore adding a duplicate throws an error.
Is it possible, without adding an additional Entity, to tell doctrine to allow duplicates on the Page--Block relation ?
Well, I'm not sure about that behavior in doctrine, but if that is the case, then you can do something that I almost always do. Represent the ManyToMany relation as two OneToMany-ManyToOne. You must create your own PageBlock entity and configure it's foreign keys.
class Page{
/**
* #var array
*
* #ORM\OneToMany(targetEntity="PageBlock", mappedBy="page", cascade={"all"})
*/
private $pageBlocks;
}
class Block{
/**
* #var array
*
* #ORM\OneToMany(targetEntity="PageBlock", mappedBy="block", cascade={"all"})
*/
private $pageBlocks;
}
class PageBlock{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \stdClass
*
* #ORM\ManyToOne(targetEntity="Page", inversedBy="pageBlocks")
* #ORM\JoinColumn(name="id_page", referencedColumnName="id")
*/
private $page;
/**
* #var \stdClass
*
* #ORM\ManyToOne(targetEntity="Block", inversedBy="pageBlocks")
* #ORM\JoinColumn(name="id_block", referencedColumnName="id")
*/
private $block;
}
As you can see the primary key remains as ID, so problem resolved. I say almost always do because this is how I do it if I need an extra attribute in the relation(almost always it happens). I suspect that could be a way of do it with the ManyToMany annotation, but there is no difference with this approach.
Hope this help you.

Unidirectional many-to-one relation in Doctrine MongoDB ODM without MongoId

I'm trying to port the following Doctrine ORM example to Doctrine ODM.
<?php
/** #Entity */
class User
{
/**
* #ManyToOne(targetEntity="Address")
* #JoinColumn(name="address_id", referencedColumnName="address_id")
*/
private $address;
}
/** #Entity */
class Address
{
// ...
}
I'm looking for the counterpart of #JoinColumn(), which I couldn't find in the documentation. Basically, I want to set the referencing field name and the referenced field name myself. How can I do this?
In MongoDB you can only reference by id, but you're not limited to using MongoID's. In fact, you can use whatever you like, including objects as id's.
This is what you should do in MongoODM, to have a property of Address act as id and User will reference Address by the value of that field. You should also set simple=true for the reference.
/**
* #Document
*/
class User
{
/**
* #ReferenceOne(targetDocument="Address", simple=true)
*/
protected $address;
}
/**
* #Document
*/
class Address
{
/**
* #Id(strategy="NONE")
*/
protected $someProperty;
}
Remember that if you change the value of that property in any of the addresses that are referenced by one or more users, that reference will become corrupt and cause some painful errors in doctrine ODM.

Symfony Doctrine2: How do I work with limited one-to-many relation?

I have an Entity Employee
class Employee
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="WorkHour", mappedBy="employee", cascade={"persist", "remove"})
*/
private $workHours;
}
and WorkHour
class WorkHour
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Profile
*
* #ORM\ManyToOne(targetEntity="Employee", inversedBy="workHours")
* #ORM\JoinColumn(name="employee_id", referencedColumnName="id")
*/
protected $profile;
/**
* #var integer
*
* #ORM\Column(name="weekday", type="smallint")
*/
private $weekday;
/**
* #var \DateTime
*
* #ORM\Column(name="hour_from", type="time")
*/
private $hourFrom;
/**
* #var \DateTime
*
* #ORM\Column(name="hour_to", type="time")
*/
private $hourTo;
}
Now I'm confused when I'm going to add addWorkHour(), removeWorkHour() methods.
Usually one-to-many relation you can add as many relations as you want, but in my case, one employee can have only up-to-7 workHours, and for a specified weekday (from 0 to 6) can have only one (or no) record.
So I think what I need is something methods like,
public function setWorkHourByWeekday($hour_from, $hour_to, $weekday);
public function getWorkHourByWeekday($weekday);
And after set workhours for an employee, when you persist that employee,
I want doctrine delete those workhours that are no longer exist, update those workhours that are changed, and create new workhours that not exist before.
How can I implement this? Should I write these logic in class Employee or its Repository, or a WorkHourManager class?
I think WorkDay is a probably better name for your entity, so i'll use that :).
$workdays= $employee->getWorkDays();
$workdays->clear(); // Clear existing workdays
// Add new workdays
foreach(...) {
$workday = new WorkDay();
$workday ->setWeekday(0); // You could use a constant like `WorkDay::MONDAY`
$workday ->setStart('09:00');
$workday ->setEnd('17:00');
$workdays->add($workday);
}
Set orphanRemoval=true on $workHours to remove WorkHours without an Employee.
The setWeekday method in your Workday entity should throw an exception when an invalid weekday is supplied (other than 0-6). You could also use a Weekday value object in combination with Doctrine embeddables.
I'd go for a service or manager class in this case.
My advice is not to drop old workhours, maybe you don't needed now, but this data could be useful in the future. So, will be better just add workHours to the Employee and make a report the get the last workHours for today. About validations, there is a lot of ways of doing that. If you are working with forms and the rules are complex maybe you need read http://symfony.com/doc/current/cookbook/validation/custom_constraint.html , but maybe you can find alternatives in the action controller or the entity class itself.

nullable self reference with composite keys using doctrine

I've got a problem with Doctrine ORM 2.5. The issue happens when I try to load instances of an entity that has an optional ManyToOne reference to itself using part of its primary key as a part of the foreign key.
The entity looks like the following:
class Category
{
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Client")
* #ORM\JoinColumn(name="client_id", referencedColumnName="client_id"))
* #var Client
*/
protected $client;
/**
* #ORM\Id
* #ORM\Column(type="string")
* #var string
*/
protected $category_id;
/**
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="parent_id", referencedColumnName="category_id", nullable=true),
* #ORM\JoinColumn(name="client_id", referencedColumnName="client_id", nullable=false)
* })
* #var Category
*/
protected $parent;
/**
* #ORM\Column(type="translated")
* #SAP\Mapping(fieldName="name")
* #var string
*/
protected $name;
}
As you can see, every child of a category must have the same client_id as its parent.
The problem seems to be that Doctrine expects the parent to exists of the foreigen key isnt empfy ( = at least one field has a non-null value). Thats obviously always true since the FK contains a part of the PK.
Is there a way to tell Doctrine that it shouldn't try to load the parent if parent_id is null?
The only alternatives I see are changing the schema by either using an artifical auto generated pk or adding a new column for the parent_client_id and make sure it equals the client_id in PHP-land.
Is there a better way?
It seems like this is a bug as reported here: https://github.com/doctrine/orm/issues/4384
From the comments on that issue setting fetch="EAGER" resolves the doctrine Missing value for primary key error. Not really a great solution, but it may work for you depending on your use case.

Zend Framework - Doctrine2: ManytoOne Mapping

OK, if anyone can help me with this that would be great, because it appears to be intractable.
I have 2 entities set up in a new zf-boilerplate project as below. I am trying to follow the tutorial on Zendcasts.com - One-to-Many with Doctrine 2, but can't get doctrine to recognise the associations I have mapped. If I run orm:schema-tool:create --dump-sql, it dumps the generated Sql, but NOT the ALTER TABLE statements at the end which should would create the Foreign Key Mapping, I can't get that to work properly.
I've tried everything I can think of, the JOIN statement I need to run obviously doesn't work either, but I figure if I can just get Doctrine to recognise the ALTER statement I can carry it from there.
Any ideas would be great, let me know if you need more info. I thought at first maybe the .ini file might be set up wrong, but I think this is more something to do with the relationship annotation?
Library/Photo/Entity/Gallery.php
<?php
namespace Photo\Entity;
/**
* #Entity(repositoryClass="Photo\Entity\Repository\MyGallery")
* #Table(name="gallery")
*/
class Gallery {
/**
* #Id #GeneratedValue
* #Column(type="smallint",nullable=false)
* #var integer
* #OneToMany(targetEntity="Photo", mappedBy="galleryID")
*/
protected $id;
/**
* #Column(type="string", length=200)
* #var string
*/
protected $gallery;
Library/Photo/Entity/Photo.php
<?php
namespace Photo\Entity;
/**
* #Entity(repositoryClass="Photo\Entity\Repository\MyPhoto")
* #Table(name="photo")
*/
class Photo {
/**
* #Id #GeneratedValue
* #Column(type="smallint",nullable=false)
* #var integer
*/
protected $id;
/**
* #Column(type="smallint",nullable=false)
* #var integer
* #ManyToOne(targetEntity="Gallery")
* #JoinColumns({
* #JoinColumn(name="gallery_id", referencedColumnName="id")
* })
*/
protected $galleryID;
Hmm... I see.. Check you column names, gallery_id vs galleryID looks suspicious.
If it is gallery_id, then you have to change the $galleryID annotation to #Column(type="smallint", nullable=false, name="gallery_id")
Generally, everywhere in the object model you should use the object field names, for example mappedBy="galleryID", but the column itself should be mapped with the appropriate DB name, like I mentioned #Column(name="gallery_id"), or for example #JoinColumns({#JoinColumn(name="gallery_id" referencedColumnName="id")})

Categories