Doctrine and inheritance mapping: association on a child entity - php

I'm trying to query an entity and joined an other entity which is a child in an inheritance mapping structure.
The situation is:
I have a parent entity (eg. Animal)
I have a child entity (eg. Dog)
I have an entity with a 1:1 association to the child (Dog House)
I want to query all the dog houses and doctrine to get me their dog owners as well.
The simple DQL query I wrote is:
SELECT o FROM MyBundle:DogHouse h JOIN h.dog d
The error is:
Notice: Undefined index: id in
../vendor/doctrine/lib/Doctrine/ORM/Query/SqlWalker.php
line 779, class: ErrorException
Looking at the stack trace it seems that doctrine is trying to join with the id on the child entity instead of the parent
Here is the classes illustrating this case
/**
* Animal
*
* #ORM\Entity
* #ORM\Table(name="animal")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="integer")
* #ORM\DiscriminatorMap({"1"="cat", "2"="dog"})
*/
class Animal
{
/**
* #ORM\Column(name="animal_id", type="integer", nullable=false)
* #ORM\Id
*/
protected $id;
/**
* #ORM\Column(name="name", type="string", length=200, nullable=false)
*/
protected $name;
/* getters, setters... */
}
/**
* Dog
*
* #ORM\Entity
* #ORM\Table(name="dog")
*/
class Dog extends Animal
{
/**
* #ORM\OneToOne(targetEntity="DogHouse", inversedBy="dog")
*/
private $dogHouse;
/* getters, setters... */
}
/**
* Dog House
*
* #ORM\Table(name="dog_house")
* #ORM\Entity
*/
class DogHouse
{
/**
* #ORM\Column(name="dog_house_id", type="integer", nullable=false)
* #ORM\Id
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="Dog", mappedBy="doghouse")
*/
private $dog;
/* getters, setters... */
}
Note:
This post relates to the exact same problem and wasn't answered

Your mappings are set up incorrectly...
The one To one relation between Dog / Doghouse should be as follows..
class DogHouse....
/**
* #ORM\OneToOne(targetEntity="Dog", mappedBy="doghouse")
*/
private $dog;
Make sure your mappedBy="doghouse"

Related

doctrine 2: inheritance mapping join with parent table

I have a base table like this:
class BaseProduct
{
/**
* #ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="baseProducts")
* #ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
**/
protected $category;
// ...
and another entity that inherit from BaseProduct
class ChildProduct extends BaseProduct
{
/**
* #ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="childProducts")
* #ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
**/
protected $category;
and Category entity:
class Category
{
/**
* #ORM\OneToMany(targetEntity="ProductBundle\Entity\BaseProduct", mappedBy="category")
* #ORM\OrderBy({"position"= "ASC"})
*/
private $baseProducts;
/**
* #ORM\OneToMany(targetEntity="ProductBundle\Entity\ChildProduct", mappedBy="category")
* #ORM\OrderBy({"position"= "ASC"})
*/
private $childProducts;
My ChildProduct table has one column named id and referenced to BaseProduct id's. Now I want to join Category with ChildProduct with this query:
$qb->select('mc', 'cp')
->from('ProductBundle:Category', 'mc')
->leftJoin('mc.childProducts', 'cp')
// .....
when I execute this query it gives this error:
ContextErrorException in SqlWalker.php line 922:
Notice: Undefined index: childProducts
While I have childProducts in Category.
Now I have two questions:
am I able to query on a parent field that does not exists in child table.
what's wrong with my query
Check doctrine chapter Inheritance Mapping: Inheritance Mapping
Following the documentation try this (I didn't test the code)
/** #ORM\MappedSuperclass */
class BaseProduct
{
/**
* #ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="baseProducts")
* #ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
**/
protected $category;
Now Doctrine knows that your class is a base class for others.
All you have to do it extend base class and add annotation #ORM\Entity
/**
* #ORM\Entity()
**/
class ChildProduct extends BaseProduct
{
/**
* #ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="childProducts")
* #ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
**/
protected $category;
I think you can remove from ChildProduct $category field. It should work also.

OneToMany ManyToOne DoctrineORM Error

I'm newbie with PHP. I started work with symfony but i have this problem
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #param \Doctrine\Common\Collections\Collection $carList
* #ORM\OneToMany(targetEntity="AppBundle\CarBundle\Entity\Car", mappedBy="name", cascade={"persist"})
*/
private $carList;
//getters and setters
}
*
* #ORM\Entity(repositoryClass="AppBundle\CarBundle\Repository\Entity\CarRepository")
* #ORM\Table(name="car")
*/
class Car
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
* #ORM\ManyToOne(targetEntity="AppBundle\UserBundle\Entity\User" , inversedBy="carList")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $name;
//getters and setters
}
The stacktrace says:
Symfony\Component\Debug\Exception\ContextErrorException: Notice: Undefined index: name
at n/a
and when i run php bin/console doctrine:schema:validate
[Mapping] FAIL - The entity-class 'AppBundle\UserBundle\Entity\User'
mapping is invalid:
* The association AppBundle\UserBundle\Entity\User#carList refers to the owning side field AppBundle\CarBundle\Entity\Car#name which is not
defined as association, but as field.
*The association AppBundle\UserBundle\Entity\User#carList refers to the owning side field Appbundle\CarBundle\Entity\Car#name which does
not exist
I have no idea whats going on, can you help me?
You are mixing up association names with column names. When you create an association you don't need to manually add the columns for that association, doctrine will work that out for you.
This code (in the Car class) says that the $name field is a normal text column in the car table, which of course is wrong
* #ORM\Column(name="name",type="string", length=100)
What you're describing is that one user can own many cars, and many cars can belong to one user. I'd then call the associations owner and cars, but you are of course free to call them whatever you want. Note that you do not need to define the join columns.
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #param \Doctrine\Common\Collections\Collection $cars
* #ORM\OneToMany(targetEntity="AppBundle\CarBundle\Entity\Car", mappedBy="owner", cascade={"persist"})
*/
private $cars;
public function __construct()
{
$this->cars = new \Doctrine\Common\Collections\ArrayCollection();
}
//getters and setters
}
 
/**
*
* #ORM\Entity(repositoryClass="AppBundle\CarBundle\Repository\Entity\CarRepository")
* #ORM\Table(name="car")
*/
class Car
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\UserBundle\Entity\User" , inversedBy="cars")
*/
private $owner;
//getters and setters
}
Read more: Doctrine association mapping
Hope it makes sense :)

Extending an entity class in doctrine

I'm trying to extend a class used as a doctrine entity, but for some reason I keep getting the error:
There is no column with name 'location_id' on table 'admin_subdivisions'
When I say extend, I mean at the php level NOT the database level. I simply want to create another table, with an extra column. I have several entities which extend the following abstract class
abstract class LocationProxy
{
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="Location", cascade={"ALL"}, fetch="LAZY")
* #ORM\JoinColumn(name="location_id", referencedColumnName="location_id", nullable=false)
*
* #var Location
*/
protected $location;
}
None of these second level classes give me any problems. Now, I want to extend this second level class
/**
* #ORM\Entity()
* #ORM\Table(name="admin_divisions")
*/
class AdminDivision extends LocationProxy
{
}
with this
/**
* #ORM\Entity()
* #ORM\Table(name="admin_subdivisions")
*/
class AdminSubDivision extends AdminDivision
{
}
but, it produces the error. Can anybody point out what I am doing wrong?
here is the Location class definition
/**
* #ORM\Entity()
* #ORM\Table(name="locations")
*/
class Location
{
/**
* #ORM\Id
* #ORM\Column(name="location_id", type="integer", options={"unsigned"=true})
*
* #var int
*/
private $id;
}
You must specify the inheritence type so that doctrine knows how to build the tables for the subclasses: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#mapped-superclasses
In you case you will need to add the following Annotations to your abstract LocationProxy Class:
#ORM\Entity
#ORM\InheritanceType("JOINED")
#ORM\DiscriminatorColumn(name="discr", type="string")
Or choose a different inheritance type
So the whole class will look like this:
/**
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
*/
abstract class LocationProxy {
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="De\Gregblog\Receipts\Location", cascade={"ALL"}, fetch="LAZY")
* #ORM\JoinColumn(name="location_id", referencedColumnName="location_id", nullable=false)
*
* #var Location
*/
protected $location;
}

Doctrine 2 OneToOne from PFK of another OneToOne association

I have one question. I'm using Doctrine 2.0 and i want to know if is possible to made OneToOne association by using PFK created by another OneToOne assotiation as you can see on the picture below.
My code looks like this:
User class:
/**
* #ORM\Entity()
*/
class User extends \Kdyby\Doctrine\Entities\IdentifiedEntity
{
/**
* #ORM\OneToOne(targetEntity="AllianceMember", mappedBy="user")
* var AllianceMember
*/
protected $allianceMembership;
}
AllianceMember class:
/**
* #ORM\Entity()
*/
class AllianceMember extends \Kdyby\Doctrine\Entities\BaseEntity
{
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="User", inversedBy="allianceMembership")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
* #var User
*/
protected $user;
/**
* #ORM\OneToOne(targetEntity="AllianceRole", mappedBy="allianceMember")
* var AllianceRole
*/
protected $role;
AllianceRole class:
/**
*
* #ORM\Entity()
*/
class AllianceRole extends \Kdyby\Doctrine\Entities\BaseEntity
{
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="AllianceMember", inversedBy="role")
* #ORM\JoinColumn(name="role_id", referencedColumnName="user_id", nullable=false)
* #var AllianceMember
*/
protected $allianceMember;
}
I'm getting this error, when I'm trying to get instance of User entity:
The column user_id must be mapped to a field in class App\Entity\AllianceMember since it is referenced by a join column of another class.
Is it even possible?
Thanks.
Yes, using mapped entities for your #Id has been possible since doctrine 2.1 see Primary key and foreign key at the same time with doctrine 2
I think you simply need to remove some of your JoinColumn statements. Since #user is already designated as your #Id, it isn't necessary to specify user_id as the JoinColumn:
/**
* #ORM\Entity()
*/
class AllianceMember extends \Kdyby\Doctrine\Entities\BaseEntity
{
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="User", inversedBy="allianceMembership")
* #var User
*/
protected $user;
/**
* #ORM\OneToOne(targetEntity="AllianceRole", mappedBy="allianceMember")
* var AllianceRole
*/
protected $role;
and
/**
*
* #ORM\Entity()
*/
class AllianceRole extends \Kdyby\Doctrine\Entities\BaseEntity
{
/**
* #ORM\Id
* #ORM\OneToOne(targetEntity="AllianceMember", inversedBy="role")
* #var AllianceMember
*/
protected $allianceMember;
}
The id of the AllianceMember is the user_id, and the id of the AllianceRole is the id of the AllianceMember, which is user_id.

Why association is not creating in Doctrine2?

I have 2 entities — NewsItem and Category. It is unidirectional association between this entities: 1 NewsItem has 1 Category, 1 Category has many NewsItem's.
I am trying to create association mapping like in THIS example. What I've tried? My code:
class NewsItem {
// other fields
/**
* #var int
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="News\Entity\Category")
*/
protected $category_id;
// other fiels, getters, setters etc
}
After that, I deleted tables in the database manually and run command orm:schema-tool:update --force in command line. It says that some queries are executed without errors — it's ok. But when I open table Category in HeidiSQL there are no FOREIGN KEYS there. That means that tables are not linked.
What I did wrong?
You can watch full code of this News\Entity\NewsItem entity here: click me. News\Entity\Category entity is here: click me.
you should remove * #ORM\Column(type="integer") as it is conflicting with the many-to-one relation.
Even if it is not the cause of the bug, you should also rename protected $category_id; to protected $category;
Also, your two entities are under the same namespace so it's not necessary to add the related entity's full path. targetEntity="Category" is enough.
You have incorrect mapping information for the Category entity.
Your NewsItem.php file should look like this:
namespace Your\Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
/**
* #ORM\Table(name="news_item")
* #ORM\Entity
*/
class NewsItem {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Category
*
* #ORM\ManyToOne(targetEntity="Category", inversedBy="news_items")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
// Rest of code omitted.
}
And your Category.php should look like this:
namespace Your\Bundle\Entity;
/**
* #ORM\Table(name="category")
* #ORM\Entity
*/
class Category {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="NewsItem", mappedBy="category")
*/
private $news_items;
public function __construct(){
$this->news_items = new ArrayCollection();
}
// Rest of code omitted.
}

Categories