integrity constraint violation 1062 with ORM and Symfony2 - php

I have an Entity with a primary key like this:
/**
* #var integer
*
* #ORM\Column(name="product_id", type="integer", nullable=false)
* #ORM\Id
*/
protected $productId;
....
/**
* Set productId
*
* #param integer $productId
* #return Products
*/
public function setProductId($productId)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId
*
* #return integer
*/
public function getProductId()
{
return $this->productId;
}
But when I try to insert an ProductId with set method, I get this error:
integrity constraint violation 1062 duplicate entry '0' for key 'primary'
I tried with * #ORM\GeneratedValue(strategy="NONE") but the result it's the same, I need to set the Product Id because the sequence isn't 1, 2, 3... is different.
And I can't create a new Id because my current ProductId is used by other entities like Foreing Keys.
Any solution?
Thanks in advance.
-----Edit with the file where I have the error-----
$prod = new Products();
$prod->setProductId("65");
$manager->persist($prod);
$manager->flush();
----Edit with whole Entity----
namespace My\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
class Products
{
/**
* #var integer
*
* #ORM\Column(name="product_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
protected $productId;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=false)
*/
private $name;
/**
* #var integer
*
* #ORM\Column(name="version", type="integer", nullable=true)
*/
private $version;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=10, nullable=false)
*/
private $code;
/**
* #var integer
*
* #ORM\Column(name="price", type="integer", nullable=false)
*/
private $price;
/**
* Set productId
*
* #param integer $productId
* #return Products
*/
public function setProductId($productId)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId
*
* #return integer
*/
public function getProductId()
{
return $this->productId;
}
/**
* Set name
*
* #param string $name
* #return Products
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set version
*
* #param integer $version
* #return Products
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Get version
*
* #return integer
*/
public function getVersion()
{
return $this->version;
}
/**
* Set code
*
* #param string $code
* #return Products
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set price
*
* #param integer $price
* #return Products
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return integer
*/
public function getPrice()
{
return $this->price;
}

When using no identifier generation strategy you should not forget that you have to assign the custom ID before you call EntityManagers persist() method.
I think you are persisting the new Entity before assigning the custom ID which means your $productId property is set to null and will be casted to 0 (zero) if you try to flush it. That will cause your error.
Doctrine Doc

Marcus post a good answer to your problem. You can solve it by adding id into you Entity, and use productId as secondary key.
Add id and set it to Auto increment, like
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
Then you can use your productId with:
/**
* #var integer
*
* #ORM\Column(name="product_id", type="integer", nullable=false)
*/
protected $productId;
With this solution you will use $productId as secondary key. Don't forget to clear data in your table.
You also have an error here:
$prod->setProductId(65);
Now you try set data which is string - in your table is integer.

Related

“association refers to the inverse side field” & “mappings are inconsistent with self”

i have one entity and is relation with self.
category is related by self and field name is parent.
when load page Mapping errors show in profiler.
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="AdminBundle\Repository\CategoryRepository")
* #UniqueEntity("urlcode")
*/
class Category
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="urlcode", type="string", length=255)
*/
private $urlcode;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255)
*/
private $image;
/**
* #var int
*
* #ORM\Column(name="digiid", type="integer", unique=true)
*/
private $digiid;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="Category")
* #ORM\JoinColumn(name="parent", referencedColumnName="id")
*/
private $parent;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Category
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set urlcode
*
* #param string $urlcode
*
* #return Category
*/
public function setUrlcode($urlcode)
{
$this->urlcode = $urlcode;
return $this;
}
/**
* Get urlcode
*
* #return string
*/
public function getUrlcode()
{
return $this->urlcode;
}
/**
* Set image
*
* #param string $image
*
* #return Category
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set digiid
*
* #param integer $digiid
*
* #return Category
*/
public function setDigiid($digiid)
{
$this->digiid = $digiid;
return $this;
}
/**
* Get digiid
*
* #return integer
*/
public function getDigiid()
{
return $this->digiid;
}
/**
* Set parent
*
* #param \AdminBundle\Entity\Category $parent
*
* #return Category
*/
public function setParent(\AdminBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \AdminBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
public function __toString()
{
return $this->title;
}
}
profiler:
The association AdminBundle\Entity\Product#category refers to the
inverse side field AdminBundle\Entity\Category#Category which does not
exist.
The association AdminBundle\Entity\Product#brand refers to the inverse
side field AdminBundle\Entity\Brand#Brand which does not exist.
The mappings AdminBundle\Entity\Product#link and
AdminBundle\Entity\Link#product are inconsistent with each other.
The association AdminBundle\Entity\Category#parent refers to the
inverse side field AdminBundle\Entity\Category#Category which does not
exist.
The association AdminBundle\Entity\Category#category refers to the
owning side field AdminBundle\Entity\Category#Category which does not
exist.
Your issue is caused by inversedBy="Category". The error says, that there's no Category::$Category atribute, and indeed there isn't.
inversedBy parameters is used to define the other side of relation in order to create bidirectional relationship.
In your case it would be probably children, if you would want to have access from parent to its children categories.
Since you don't have it, you cane simply remove this parameter. And it looks like you have this parameter used incorrectly also in other entities.
If you want more information about how to define relationships in Doctrine ORM, take a look at documentation

Symfony doesnt auto increment id

I have a database called cardb which is populated by a SQL file which made some cars. They have ID's starting from 1 up to 30. When I try to create new Car it works the first time and creates a car with id 0 then when it tries to do it again it again tries to make an entry with 0.
Here is the error
An exception occurred while executing 'INSERT INTO cars (Make, Model, TravelledDistance) VALUES (?, ?, ?)' with params ["fock", "fock", 320]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'
Here is my entity
/**
* Cars
*
* #ORM\Table(name="cars")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CarsRepository")
*/
class Cars
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Make", type="string", length=255)
*/
private $make;
/**
* #var string
*
* #ORM\Column(name="Model", type="string", length=255)
*/
private $model;
/**
* #var int
*
* #ORM\Column(name="TravelledDistance", type="bigint")
*/
private $travelledDistance;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Parts", inversedBy="cars")
* #ORM\JoinTable(
* name="PartCars",
* joinColumns={
* #ORM\JoinColumn(name="Part_Id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="Car_Id", referencedColumnName="id")
* })
*/
private $parts;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set make
*
* #param string $make
*
* #return Cars
*/
public function setMake($make)
{
$this->make = $make;
return $this;
}
/**
* Get make
*
* #return string
*/
public function getMake()
{
return $this->make;
}
/**
* Set model
*
* #param string $model
*
* #return Cars
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* Get model
*
* #return string
*/
public function getModel()
{
return $this->model;
}
/**
* Set travelledDistance
*
* #param integer $travelledDistance
*
* #return Cars
*/
public function setTravelledDistance($travelledDistance)
{
$this->travelledDistance = $travelledDistance;
return $this;
}
/**
* Get travelledDistance
*
* #return int
*/
public function getTravelledDistance()
{
return $this->travelledDistance;
}
/**
* #return mixed
*/
public function getParts()
{
return $this->parts;
}
}
It is auto generated Entity which has auto increment annotation.
What could be the problem?
The annotation
* #ORM\GeneratedValue(strategy="AUTO")
won't make PHP create a unique ID. You can see from the insert statement that PHP doesn't provide an ID value at all.
That annotation tells the ORM what kind of column it is, but it depends on the database to generate the value. You can check the documentation for more details.
Based on the way your code looks, it appears you used the console to generate the entity, but I assume the fact that the database isn't doing the id properly means that you created the cars table by hand rather than using doctrine:schema:update, which is fine if that's the way you need/want to do it, but you'll have to alter your table to make the id column an autoincrement.

symfony, "Missing value for primary key usn on GameBackend\Entity\CrossFire\Fame"

I am frustrated.. I have added the JoinColumn for both values, yet it outputs
Missing value for primary key famepoint on GameBackend\Entity\CrossFire\Fame
Character.php
/**
* #var Fame
*
* #ORM\OneToOne(targetEntity="Fame")
* #ORM\JoinColumn(name="LEV", referencedColumnName="FAME_GRADE")
*/
private $level = 0;
/**
* #return Fame
*/
public function getLevel()
{
return $this->level;
}
/**
* #param Fame $level
* #return self
*/
public function setLevel($level)
{
$this->level = $level;
return $this;
}
Fame.php
{
/**
* #var integer
*
* #ORM\Column(name="USN", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $usn;
/**
* #var integer
*
* #ORM\Column(name="FAME_POINT", type="integer", nullable=false)
*/
private $famepoint = 0;
/**
* #var integer
*
* #ORM\Column(name="FAME_GRADE", type="integer", nullable=false)
*/
private $famelevel = 0;
/**
* #return int
*/
public function getId()
{
return $this->usn;
}
/**
* #param int $usn
* #return self
*/
public function setId($usn)
{
$this->usn = $usn;
return $this;
}
/**
* #return string
*/
public function getfamepoint()
{
return $this->famepoint;
}
/**
* #param string $famepoint
* #return self
*/
public function setfamepoint($famepoint)
{
$this->famepoint = $famepoint;
return $this;
}
/**
* #return int
*/
public function getfamelevel()
{
return $this->famelevel;
}
/**
* #param int $famelevel
* #return self
*/
public function setfamelevel($famelevel)
{
$this->famelevel = $famelevel;
return $this;
}
}
Notice: I am relatively new to this and I have absolutely no clue what may cause the issue, I have read through multiple topics and nothing helped me so far.
Kind regards.
referencedColumnName inside your annotation should be Name of the primary key identifier that is used for joining of this relation as stated in http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html And your $famelevel actually isn't. I belive that you should refer to $usn field in your association as it is actual primary key of your Fame entity that you joining. Hope that will help!

Symfony 2.8 Catchable Fatal Error: Object of class ... could not be converted to string (one to many and many to one)

This is my first question here, so please forgive me if I omitted something.
I have 2 entities defined: Product and Category.
<?php
namespace Backend\AdminBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="Backend\AdminBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, unique=true)
*/
private $name;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var int
*
* #ORM\Column(name="parent_id", type="integer")
*/
private $parentId;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set status
*
* #param integer $status
* #return Category
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set parentId
*
* #param integer $parentId
* #return Category
*/
public function setParentId($parentId)
{
$this->parentId = $parentId;
return $this;
}
/**
* Get parentId
*
* #return integer
*/
public function getParentId()
{
return $this->parentId;
}
}
and
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* #ORM\Table(name="product")
* #ORM\Entity(repositoryClass="Backend\AdminBundle\Repository\ProductRepository")
*/
class Product
{
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="short_description", type="string", length=255)
*/
private $shortDescription;
/**
* #var string
*
* #ORM\Column(name="full_description", type="text")
*/
private $fullDescription;
/**
* #var float
*
* #ORM\Column(name="price", type="float")
*/
private $price;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var int
*
* #ORM\Column(name="category_id", type="integer")
*/
private $categoryId;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set shortDescription
*
* #param string $shortDescription
* #return Product
*/
public function setShortDescription($shortDescription)
{
$this->shortDescription = $shortDescription;
return $this;
}
/**
* Get shortDescription
*
* #return string
*/
public function getShortDescription()
{
return $this->shortDescription;
}
/**
* Set fullDescription
*
* #param string $fullDescription
* #return Product
*/
public function setFullDescription($fullDescription)
{
$this->fullDescription = $fullDescription;
return $this;
}
/**
* Get fullDescription
*
* #return string
*/
public function getFullDescription()
{
return $this->fullDescription;
}
/**
* Set price
*
* #param float $price
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set status
*
* #param integer $status
* #return Product
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set categoryId
*
* #param integer $categoryId
* #return Product
*/
public function setCategoryId($categoryId)
{
$this->categoryId = $categoryId;
return $this;
}
/**
* Get categoryId
*
* #return integer
*/
public function getCategoryId()
{
return $this->categoryId;
}
/**
* Set category
*
* #param \Backend\AdminBundle\Entity\Category $category
* #return Product
*/
public function setCategory(\Backend\AdminBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Backend\AdminBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
I've managed to properly set the relation between them as Category has Many Product and Product has one Category.
I successfully created my CRUD for Category and it works.
I was able to create my CRUD for Product, accessed the index route and works just fine.
The issue is that when I try to create a new Product I get the following exception:
Catchable Fatal Error: Object of class Backend\AdminBundle\Entity\Category could not be converted to string
It's my first Symfony test project and beside being a total noob, I'm stuck. I know I must be omitting something extremely obvious but I just can't tell what.
I'm using Symfony 2.8.
What am I doing wrong?
Define a magic method __toString() for your Category entity.
For sample, do it like this:
public function __toString()
{
return $this->getName();
}

Symfony, Cannot retrieve record from table

In Symfony I cannot retrieve a record from a table using a find(), but I can using createQuery()? This is happening randomly on my tables in my project. The data just seem to become unaccessable using symfony find(), findBy() etc, but I can use dql???
Why is this happening? Has anyone ever had this happen? I cannot figure this out. Thanks for helping!
Test I've Ran: I've created a similar table using the exact same entity fields and imported the data into the table and it works absolutely fine. Why has this table just stopped responding to Symfony's request?
This Works
$dql = "SELECT co FROM WIC\CommonBundle\Entity\CustomOptions co WHERE co.account=:account_id AND co.option_field=:value";
$query = $em->createQuery($dql);
$query->setParameters(array(
'value' => 'reorder_reason',
));
$customOptionValue = $query->getResult();
echo count($customOptionValue); // equals 3
This DOES NOT Work - Exact same variables are passed in
$customOptionValue = $em->getRepository('WICCommonBundle:CustomOptions')->findBy(
array(
"option_field"=>"reorder_reason",
)
);
echo count($customOptionValue); // equals 0
Here is my CustomOptions entity:
namespace WIC\CommonBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* CustomOptions
*
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="accountFieldValueOptions", columns={"account_id", "option_value", "option_field"})})
* #ORM\Entity(repositoryClass="WIC\CommonBundle\Entity\CommonRepository")
* #Gedmo\Loggable
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
* #ORM\HasLifecycleCallbacks
*/
class CustomOptions
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
*
* #Gedmo\Versioned
* #ORM\Column(name="name", type="string", length=255, unique=false, nullable=true)
*/
private $name;
/**
* #var string $option_value
*
* #Gedmo\Versioned
* #ORM\Column(name="option_value", type="string", length=255)
* #Assert\NotBlank(message="Option Value Should Not Be Blank")
*/
private $option_value;
/**
* #var string $option_field
*
* #Gedmo\Versioned
* #ORM\Column(name="option_field", type="string", length=255, unique=false, nullable=true)
*/
private $option_field;
/**
* #ORM\ManyToOne(targetEntity="WIC\AccountBundle\Entity\Account", fetch="EAGER")
* #ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false)
* #Gedmo\Versioned
*/
protected $account;
/**
* #var datetime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime", nullable=true)
*/
private $created;
/**
* #var datetime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime", nullable=true)
*/
private $updated;
/**
* #ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
private $deletedAt;
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set account
*
* #param \WIC\AccountBundle\Entity\Account $account
* #return InventoryLocation
*/
public function setAccount(\WIC\AccountBundle\Entity\Account $account = null)
{
$this->account = $account;
return $this;
}
/**
* Get account
*
* #return \WIC\AccountBundle\Entity\Account
*/
public function getAccount()
{
return $this->account;
}
/**
* Set created
*
* #param \DateTime $created
* #return CustomOptions
*/
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 CustomOptions
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set deletedAt
*
* #param \DateTime $deletedAt
* #return CustomOptions
*/
public function setDeletedAt($deletedAt)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Get deletedAt
*
* #return \DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
/**
* Get option_value
*
* #return string
*/
public function getOptionValue()
{
return $this->option_value;
}
/**
* Set option_value
*
* #param string $option_value
* #return CustomOptions
*/
public function setOptionValue($option_value)
{
$this->option_value = $option_value;
}
/**
* Get option_field
*
* #return string
*/
public function getOptionField()
{
return $this->option_field;
}
/**
* Set option_field
*
* #param string $option_field
* #return CustomOptions
*/
public function setOptionField($option_field)
{
$this->option_field = $option_field;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set name
*
* #param string $name
* #return CustomOptions
*/
public function setName($name)
{
$this->name = $name;
}
Try using the ID instead of the entire object
I.e.
$customOptionValue = $em->getRepository('WICCommonBundle:CustomOptions')->findBy(array(
"account"=>$account->getId(),
"option_field"=>"reorder_reason",
));
Edit: it's your failure to follow the coding standards expected by symfony that caused this issue for you:
Use camelCase, not underscores, for variable, function and method names
private $option_field should become private $optionField and you should adjust any functions you created to reflect this. Then your findBy array will use "optionField"=>"reorder_reason"
I see that you are using soft #Gedmo\SoftDeleteable. Can you please check if the record that exists and can not be retreived does not have deletedAt set?
Doctrine queries are ignoring record, where deletedAt is set. But lets say "not doctrine queries" would still be able to find these records.

Categories