When a try update my database I got error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
(symfony.#sql-d8c_55, CONSTRAINT FK_957A6479A233CB39 FOREIGN KEY
(klient_id) REFERENCES klient (id))
My class user:
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* Class User
* #package AppBundle\Entity
*
* #ORM\Table("fos_user")
* #ORM\Entity()
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Klient", inversedBy="users")
* #ORM\JoinColumn(nullable=false)
*/
private $klient;
/**
* #return mixed
*/
public function getKlient()
{
return $this->klient;
}
/**
* #param mixed $klient
*/
public function setKlient($klient)
{
$this->klient = $klient;
}
public function __construct()
{
parent::__construct();
}
}
class Klient
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Klient
*
* #ORM\Table(name="klient")
* #ORM\Entity(repositoryClass="AppBundle\Repository\KlientRepository")
*/
class Klient
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nazwa", type="string", length=255, unique=true)
*/
private $nazwa;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\User", mappedBy="klient")
*/
private $users;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set nazwa
*
* #param string $nazwa
*
* #return Klient
*/
public function setNazwa($nazwa)
{
$this->nazwa = $nazwa;
return $this;
}
/**
* Get nazwa
*
* #return string
*/
public function getNazwa()
{
return $this->nazwa;
}
public function __construct()
{
$this->users = new ArrayCollection();
}
}
in my opinion you have this error because you already have datas in your database. When you try to add the foreign key on your user table, kcient_id is null. And in your definition, you specify nullable: false.
I suggest you proceed in two times.
Edit your annotation to nullable: true, update your database and link your client to klient
Re-edit your annotation to nullable: false, it should be ok
Related
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 :(
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 big understanding problem with OneToMany Relationship - i searched a lot but that didnt help, maybe someone can help me with this.
I have a Event Entity with OneToMany Relation
<?php
namespace #\#\#;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Turmforum\BookingBundle\Entity\Contact;
/**
* Event
*
* #ORM\Table(name="events")
* #ORM\Entity
*/
class Event
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Contact", mappedBy="event")
*/
protected $event_contacts;
/**
*
*/
public function __construct() {
$this->contacts = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getContacts() {
return $this->contacts;
}
public function addContact(Contact $contact) {
$this->contacts[] = $contact;
return $this;
}
And have a Contact Entity with ManyToOne Relation
<?php
namespace #\#\#;
use Doctrine\ORM\Mapping as ORM;
use Turmforum\BookingBundle\Entity\Event;
/**
* Contact
*
* #ORM\Table(name="contacts")
* #ORM\Entity
*/
class Contact
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Event", inversedBy="event_contacts")
* #ORM\JoinColumn(name="event_id", referencedColumnName="id")
*/
protected $event;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getEvent() {
return $this->event;
}
When i try to save my event details over a form i get the error:
Neither the property "event_id" nor one of the methods "getEventId()",
"eventId()", "isEventId()", "hasEventId()", "__get()" exist and have
public access in class "Turmforum\BookingBundle\Entity\Event".
What am i missing?
I use the auto-generated getters in a class table inheritance setup in a Symfony project. getId() returns null, while every other getter works. Can you spot any problem? What should I search for? I imported the database entries manually, but I don't think that is the cause.
The abstract parent entity
//src/Acme/WebzineBundle/Entity/Content.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Content
*
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="heading", type="integer")
* #ORM\DiscriminatorMap({
* 0 = "Review"
* })
*/
abstract class Content
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="edited", type="date")
*/
private $edited;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get edited
*
* #return \DateTime
*/
public function getEdited()
{
return $this->edited;
}
}
The child entity
//src/Acme/WebzineBundle/Entity/Review.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Review articles
*
* #ORM\Table()
* #ORM\Entity
*/
class Review extends Content
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=127)
*/
private $title;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
}
The next foreign key constraint is on the table of the child entity:
CONSTRAINT `FK_7EEF84F0BF396750` FOREIGN KEY (`id`) REFERENCES `Content` (`id`)
ON DELETE CASCADE
The query
//src/Acme/AdminBundle/Controller/MainController.php
namespace Acme\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class MainController extends Controller
{
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT post FROM AcmeWebzineBundle:Content post
ORDER BY post.edited DESC'
);
$query->setMaxResults(30);
$posts = $query->getResult();
$latest_post = $posts[0];
return $this->render('AcmeAdminBundle:Main:index.html.twig', array(
'posts' => $posts,
'id' => gettype($latest_post->getId()), // This returns null!
'edited' => $latest_post->getEdited(), // Any other getter works
'title' => $latest_post->getTitle(), // also from the child entity.
));
}
}
You need to remove the id property and getId() method from the child class
//src/Acme/WebzineBundle/Entity/Review.php
namespace Acme\WebzineBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Review articles
*
* #ORM\Table()
* #ORM\Entity
*/
class Review extends Content
{
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=127)
*/
private $title;
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
}
You can not create object of Content class.
And better use only unique properties and methods in Review class, because others are inherited from abstract Content class.
I'm trying to create the database tables using Symfony command's using the following line :
php app/console doctrine:schema:create
I obtain the following error :
[Doctrine\ORM\Mapping\MappingException]
No identifier/primary key specified for Entity "Cupon\CiudadBundle\Entity\Ciudad". Every Entity must have an identifier/primary key.
And it's the above class :
namespace Cupon\TiendaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** #ORM\Entity */
class Tienda
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/** #ORM\ManyToOne(targetEntity="Cupon\CiudadBundle\Entity\Ciudad") */
protected $ciudad;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set ciudad
*
* #param \Cupon\CiudadBundle\Entity\Ciudad $ciudad
* #return Tienda
*/
public function setCiudad(\Cupon\CiudadBundle\Entity\Ciudad $ciudad = null)
{
$this->ciudad = $ciudad;
return $this;
}
/**
* Get ciudad
*
* #return \Cupon\CiudadBundle\Entity\Ciudad
*/
public function getCiudad()
{
return $this->ciudad;
}
public function __toString()
{
return $this->getNombre();
}
}
I don't understand whats really happen, because I put the ID for the class. Any help is appreciated.
Just check if the Ciudad Entity has an id
You should include the following annotations for example:
namespace Cupon\TiendaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** #ORM\Entity */
class Ciudad
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
//..