I'm trying to save data with ManyToOne relations in a DataFixtures class. And I get this error on saving data.
Please, help me.
Sources:
Entity/DealsCategory.php:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* DealsCategory
*
* #ORM\Table(name="deals_category")
* #ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryRepository")
*/
class DealsCategory
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="alias", type="string", length=50, nullable=true)
*/
private $alias;
/**
* #ORM\OneToMany(targetEntity="DealsCategoryLang", mappedBy="category")
*/
protected $categoryLang;
/**
* #return mixed
*/
public function getCategoryLang()
{
return $this->categoryLang;
}
/**
* #param DealsCategoryLang $categoryLang
*/
public function setCategoryLang(DealsCategoryLang $categoryLang = null)
{
$this->categoryLang = $categoryLang;
}
/**
* #param DealsCategoryLang $categoryLang
*/
public function setOneCategoryLang(DealsCategoryLang $categoryLang)
{
$this->categoryLang[] = $categoryLang;
}
/**
* DealsCategory constructor.
*/
public function __construct()
{
$this->categoryLang = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set alias
*
* #param string $alias
*
* #return DealsCategory
*/
public function setAlias($alias)
{
$this->alias = $alias;
return $this;
}
/**
* Get alias
*
* #return string
*/
public function getAlias()
{
return $this->alias;
}
}
Entity/DealsCategoryLang.php:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* DealsCategoryLang
*
* #ORM\Table(name="deals_category_lang")
* #ORM\Entity(repositoryClass="AppBundle\Repository\DealsCategoryLangRepository")
*/
class DealsCategoryLang
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="catId", type="integer")
*/
private $catId;
/**
* #var string
*
* #ORM\Column(name="lang", type="string", length=10)
*/
private $lang;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=70)
*/
private $title;
/**
* #ORM\ManyToOne(targetEntity="DealsCategory", inversedBy="categoryLang", cascade={"persist"})
* #ORM\JoinColumn(name="catId", referencedColumnName="id")
*
*/
protected $category;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set catId
*
* #param integer $catId
*
* #return DealsCategoryLang
*/
// public function setCatId($catId)
// {
// $this->catId = $catId;
//
// return $this;
// }
/**
* Get catId
*
* #return int
*/
public function getCatId()
{
return $this->catId;
}
/**
* Set lang
*
* #param string $lang
*
* #return DealsCategoryLang
*/
public function setLang($lang)
{
$this->lang = $lang;
return $this;
}
/**
* Get lang
*
* #return string
*/
public function getLang()
{
return $this->lang;
}
/**
* Set title
*
* #param string $title
*
* #return DealsCategoryLang
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
}
DataFixtures/ORM/LoadCategories.php
<?php
namespace AppBundle\DataFixtures\ORM;
use AppBundle\Entity\DealsCategory;
use AppBundle\Entity\DealsCategoryLang;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadCategories implements FixtureInterface, ContainerAwareInterface
{
private $container;
/**
* Load data fixtures with the passed EntityManager
*
* #param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
$category = new DealsCategory();
$categoryLang = new DealsCategoryLang();
$categoryLang->setLang('en');
$categoryLang->setTitle('Food and Drinks');
$category->setOneCategoryLang($categoryLang);
$manager->persist($category);
$manager->persist($categoryLang);
$manager->flush();
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
I've tried it in different ways, but it's still not working. Tell me please, what i am doing wrong?
UPD:
my errors are:
[Doctrine\DBAL\Exception\NotNullConstraintViolationException]
An exception occurred while executing 'INSERT INTO deals_category_lang (catId, lang, title) VALUES (?, ?, ?)' with params [null, "en", "Food and Drinks"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null
PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'catId' cannot be null
I am running the fixtures through the command line:
php bin/console doctrine:fixtures:load --append
Ok, I resolved it...
The problem was in my Fixture class:
Instead of
$category->setOneCategoryLang($categoryLang);
I should put the
$categoryLang->setCategory($category);
,respecting the hierarchy of my entities' relations :(
Related
Tags Entity :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="tags", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class Tags extends Entity {
/**
* Many Tags have Many HolidayPackages.
* #ManyToMany(targetEntity="HolidayPackages", mappedBy="tags")
* #JoinTable(name="holiday_tags",
* joinColumns={#JoinColumn(name="tid", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="hpid", referencedColumnName="id")}
* )
*/
protected $holiday_packages;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $tags;
/**
* #return mixed
*/
public function getHolidayPackages() {
return $this->holiday_packages;
}
/**
* #param mixed $holiday_packages
*/
public function setHolidayPackages($holiday_packages) {
$this->holiday_packages = $holiday_packages;
}
/**
* #return string
*/
public function getTags() {
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags) {
$this->tags = $tags;
}
}
Holiday Packages :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="holiday_packages", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class HolidayPackages extends Entity {
/**
* Many HolidayPackages have Many Tags.
* #ManyToMany(targetEntity="Tags", inversedBy="holiday_packages")
* #JoinTable(name="holiday_tags",
* joinColumns={#JoinColumn(name="hpid", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="tid", referencedColumnName="id")}
* )
*/
protected $tags;
/**
* #return mixed
*/
public function getTags() {
return $this->tags;
}
/**
* #param mixed $tags
*/
public function setTags($tags) {
$this->tags = $tags;
}
}
I am trying to create many-to-many assocation mapping. I follow this link :
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html to make this mapping.
But when i try to update doctrine, error occure :
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'ALTER TABLE holiday_tags DROP PRIMARY KEY':
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
orm:schema-tool:update [--complete] [--dump-sql] [--force]
UPDATE
Entity Class :
<?php
namespace App;
use Doctrine\ORM\Mapping as ORM;
/**
* #MappedSuperclass
* #HasLifecycleCallbacks()
*/
abstract class Entity
{
/**
* #var integer
*
* #Column(name="id", type="integer")
* #Id
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Column(type="datetime")
* #var \DateTime
*/
protected $created_at;
/**
* #Column(type="datetime", nullable=true)
* #var \DateTime
*/
protected $updated_at;
/**
* Constructor
*/
public function __construct() {
$this->setCreatedAt(new \DateTime());
$this->setUpdatedAt(new \DateTime());
}
/**
* #PreUpdate
*/
public function setUpdatedValue() {
$this->setUpdatedAt(new \DateTime());
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* #param $created_at
*/
public function setCreatedAt($created_at) {
$this->created_at = $created_at;
}
/**
* #return \DateTime
*/
public function getCreatedAt() {
return $this->created_at->format('d/m/Y H:i');
}
/**
* #param $updated_at
*/
public function setUpdatedAt($updated_at) {
$this->updated_at = $updated_at;
}
/**
* #return \DateTime
*/
public function getUpdatedAt() {
return $this->updated_at;
}
}
It creates a class holidaypackages_tags but still give error and i specified name as holiday_tags but it named holidaypackages_tags...
You are trying to create the same table twice "holiday_tags"!
Try this:
class Tags extends Entity {
/**
* Many Tags have Many HolidayPackages.
* #ManyToMany(targetEntity="HolidayPackages", mappedBy="tags")
*/
protected $holiday_packages;
//...
}
class HolidayPackages extends Entity {
/**
* Many HolidayPackages have Many Tags.
* #ManyToMany(targetEntity="Tags", inversedBy="holiday_packages")
* #JoinTable(name="holiday_tags",
* joinColumns={#JoinColumn(name="hpid", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="tid", referencedColumnName="id")}
* )
*/
protected $tags;
//...
}
Notice that there is no annotation to create the same table again on $holiday_packages field
I have an entity with an
integer column (compositeId)
and a
string column (asin)
I want both columns working as a composite key.
So I look here in the documentation:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html
But when I try to load my repository
$myEntity = $em->getRepository(MyEntity::class);
I got this error message:
single id is not allowed on composite primary key in entity
AppBundle\Entity\MyEntity
This is my Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #Entity(repositoryClass="AppBundle\Repository\MyEntityRepository")
* #Table(name="my_entity")
*/
class MyEntity {
/**
* #Column(type="integer")
* #GeneratedValue()
*/
protected $id;
/**
* #var integer
* #Id
* #Column(type="integer", name="composite_id")
*/
protected $compositeId;
/**
* #var string
* #Id
* #Column(type="string", name="asin")
*/
protected $asin;
/**
* #var string
* #Column(type="string", name="sku")
*/
protected $sku;
/**
* #var string
* #Column(type="string", name="ean")
*/
protected $ean;
/**
* #codeCoverageIgnore
* #return mixed
*/
public function getId() {
return $this->id;
}
/**
* #param mixed $id
*
* #return MyEntity;
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* #codeCoverageIgnore
* #return int
*/
public function getCompositeId() {
return $this->compositeId;
}
/**
* #param int $compositeId
*
* #return MyEntity;
*/
public function setCompositeId($compositeId) {
$this->compositeId = $compositeId;
return $this;
}
/**
* #codeCoverageIgnore
* #return string
*/
public function getAsin() {
return $this->asin;
}
/**
* #param string $asin
*
* #return MyEntity;
*/
public function setAsin($asin) {
$this->asin = $asin;
return $this;
}
/**
* #codeCoverageIgnore
* #return string
*/
public function getSku() {
return $this->sku;
}
/**
* #param string $sku
*
* #return MyEntity;
*/
public function setSku($sku) {
$this->sku = $sku;
return $this;
}
/**
* #codeCoverageIgnore
* #return string
*/
public function getEan() {
return $this->ean;
}
/**
* #param string $ean
*
* #return MyEntity;
*/
public function setEan($ean) {
$this->ean = $ean;
return $this;
}
}
What am I doing wrong?
When I remove #generatedValue at my ID table it works.
But I need auto generated values at my ID column.
I don't have any #Id annotation at my ID column, only #generatedValue, and on my both #Id columns I don't have any annotation with #generatedValue but I got this error ...
Doctrine only supports #GeneratedValue() on #Id fields.
This annotation is optional and only has meaning when used in conjunction with #Id.
https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref_generatedvalue
You may be able to use columnDefinition as a workaround, e.g.
#ORM\Column(type="integer", name="id", columnDefinition="INT AUTO_INCREMENT")
as suggested here: https://stackoverflow.com/a/34749619/380054
You need to remove all #Id in properties description except protected $id.
I'm under Symfony 3.0.6
I use loadFixtures with this Entity :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CategorieRepository")
*/
class Categorie
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Libelle", type="string", length=100)
*/
private $libelle;
/**
* #var datetime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\User", inversedBy="categories")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $user;
public function __construct()
{
$this->createdAt = new \DateTime('now');
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libelle
*
* #param string $libelle
*
* #return Categorie
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set user
*
* #param \AppBundle\Entity\User $user
*
* #return Categorie
*/
public function setUser(User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \AppBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set createdAt
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* Get createdAt
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}
And when i try to insert some values with this :
public function loadCategorie(ObjectManager $manager, $user)
{
$aLib = array('Categ1','Categ2','Categ3','Categ4','Categ5','Categ6','Categ7');
foreach($aLib as $catP)
{
$cat = new Categorie();
$cat->setLibelle("[".$user->getUsername()."] ".$catP);
$cat->setUser($user);
$manager->persist($cat);
}
$manager->flush();
}
I have this error :
[Doctrine\DBAL\Exception\NotNullConstraintViolationException]
An exception occurred while executing 'INSERT INTO categorie (Libelle, created_at, user_id) VALUES (?, ?, ?)' with
params ["[cyriladmin] Categ1", null, 1]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null
any ideas ?
You have a bug in the entity: private $created_at; vs $this->createdAt = new \DateTime('now'); <- different variables names.
When i tried to update my database i got this error:
i'm not sure but I think the error means that the value for column tva_id on table fly
you are inserting doesn't exist on table tva. when i check in phpmyadmin tva(id)) should be link to(tva_id)` in table Post but is not. what should i do to fix this error ?
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'ALTER TABLE post ADD CONSTRAINT
FK_5 A8A6C8D4D79775F FOREIGN KEY (tva_id) REFERENCES tva (id)':
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(fly.#sql-93c_155, CONSTRAI NT FK_5A8A6C8D4D79775F FOREIGN
KEY (tva_id) REFERENCES tva (id))
Tva.php
<?php
namespace FLY\BookingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Tva
*
* #ORM\Table("tva")
* #ORM\Entity(repositoryClass="FLY\BookingsBundle\Entity\TvaRepository")
*/
class Tva
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="multiplicate", type="float")
*/
private $multiplicate;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=125)
*/
private $name;
/**
* #var float
*
* #ORM\Column(name="value", type="float")
*/
private $value;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set multiplicate
*
* #param float $multiplicate
* #return Tva
*/
public function setMultiplicate($multiplicate)
{
$this->multiplicate = $multiplicate;
return $this;
}
/**
* Get multiplicate
*
* #return float
*/
public function getMultiplicate()
{
return $this->multiplicate;
}
/**
* Set name
*
* #param string $name
* #return Tva
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set value
*
* #param float $value
* #return Tva
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return float
*/
public function getValue()
{
return $this->value;
}
}
post.php
<?php
namespace FLY\BookingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use JMS\SecurityExtraBundle\Annotation\Secure;
/**
* Post
*
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="FLY\BookingsBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="FLY\BookingsBundle\Entity\Tva", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $tva;
/**
*
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
* #ORM\JoinColumn(onDelete="CASCADE")
* #Security("user.getId() == post.getOwner()")
*/
private $owner;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return User
*/
public function getOwner()
{
return $this->owner;
}
/*
* #param User $owner
*/
public function setOwner(User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Set tva
*
* #param \FLY\BookingsBundle\Entity\Tva $tva
* #return Post
*/
public function setTva(\FLY\BookingsBundle\Entity\Tva $tva)
{
$this->tva = $tva;
return $this;
}
/**
* Get tva
*
* #return \FLY\BookingsBundle\Entity\Tva
*/
public function getTva()
{
return $this->tva;
}
}
user.php
<?php
namespace Application\Sonata\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use ArrayIterator;
use Closure;
use Doctrine\Common\Collections\Expr\ClosureExpressionVisitor;
/**
* This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/easy-extends )
*
*/
/**
* #ORM\Entity(repositoryClass="FLY\UserBundle\Repository\UserRepository")
* #ORM\Table(name="fos_user_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
$this->commandes = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\OneToMany(targetEntity="FLY\BookingsBundle\Entity\Commandes", mappedBy="user", cascade={"remove"})
* #ORM\JoinColumn(nullable=true)
*/
private $commandes;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add commandes
*
* #param \FLY\BookingsBundle\Entity\Commandes $commandes
* #return User
*/
public function addCommande(\FLY\BookingsBundle\Entity\Commandes $commandes)
{
$this->commandes[] = $commandes;
return $this;
}
/**
* Remove commandes
*
* #param \FLY\BookingsBundle\Entity\Commandes $commandes
*/
public function removeCommande(\FLY\BookingsBundle\Entity\Commandes $commandes)
{
$this->commandes->removeElement($commandes);
}
/**
* Get commandes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCommandes()
{
return $this->commandes;
}
}
I have a table items with item_id, item_title, ... . I also have a table articles with a PK item_id that is a FK from the table items and a field article_body. I also have a many to many relationship from items to categories (item_has_catogories).
This is my Article Entity:
<?php
namespace Dxsolutions\DxsolutionsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Item
*
* #ORM\Table(name="articles")
* #ORM\Entity
*/
class Article extends Item
{
/**
* #var string
*
* #ORM\Column(name="article_body", type="text")
*/
protected $body;
/**
* Set body
*
* #param string $body
* #return Article
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body
*
* #return string
*/
public function getBody()
{
return $this->body;
}
}
As you can see my Article Entity extends from the Item Entity, my Item Entity:
<?php
namespace Dxsolutions\DxsolutionsBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Item
*
* #ORM\Table(name="items")
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="item_type", type="string")
* #ORM\DiscriminatorMap({"ITEM"="Item", "ARTICLE"="Article"})
*/
class Item
{
/**
* #var integer
*
* #ORM\Column(name="item_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="item_title", type="string", length=255)
*/
private $title;
/**
* #var \DateTime
*
* #ORM\Column(name="item_created", type="datetimetz")
*/
private $created;
/**
* #var \DateTime
*
* #ORM\Column(name="item_modified", type="datetimetz")
*/
private $updated;
/**
* #var \DateTime
*
* #ORM\Column(name="item_deleted", type="datetimetz")
*/
private $deleted;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Category", inversedBy="items")
* #ORM\JoinTable(name="items_has_categories",
* joinColumns={#ORM\JoinColumn(name="item_id", referencedColumnName="item_id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="category_id")}
* )
*/
protected $categories;
/**
* Constructor has to create Doctrine ArrayCollections
*/
public function __construct()
{
$this->categories = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Item
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set created
*
* #param \DateTime $created
* #return Item
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Item
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set deleted
*
* #param \DateTime $deleted
* #return Item
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return \DateTime
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set category
*
* #param Category $category
*/
public function setCategories(Category $category)
{
$this->categories->add($category);
}
/**
* Get categories
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getCategories()
{
return $this->categories;
}
}
Now I would like to delete an article (= an item).
This is what I do :
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository('DxSolutionsBundle:Article')->find($id);
foreach($article->getCategories() as $c) {
$article->getCategories()->removeElement($c);
$em->flush();
}
$em->remove($article);
$em->flush();
But I always get this error:
An exception occurred while executing 'DELETE FROM items WHERE item_id = ?' with params [4]:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`dx-solutions`.`articles`, CONSTRAINT `fk_articles_items1` FOREIGN KEY (`item_id`) REFERENCES `items` (`item_id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
What am I doing wrong?
The answer was as Hast said that I didn't defined 'CASCADE ON DELETE' at my FK item_id in my article table.