我是Symfony2和Doctrine的新手,我有点卡住了。保存到数据库时收到错误。
An exception occurred while executing 'INSERT INTO tho_provider (provid_name, provid_logo, provid_logo_path, created_time, provider_created_by) VALUES (?, ?, ?, ?, ?)' with params ["test", {}, "qwwwww", "2015-08-11 16:03:15", null]:
SQLSTATE [23000]:完整性约束违规:1048列'provider_created_by'不能为空
我有一个表单,其中我只获取提供者名称输入和徽标,其余是我在控制器中处理,包括provider_created_by,它在刷新后立即获取null,在flush命令显示值之前。
public function createAction(Request $request)
{
$user = $this->getUser();
$entity = new Provider();
$entity->setProvidLogoPath("qwwwww");
$entity->setProviderCreatedBy($user);
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
//$entity->setCreatedBy($user);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('provider_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
我有实体,PROVIDER和USER。 用户可以创建许多提供者,提供者只属于一个用户。一对多关系。
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Provider
*
* @ORM\Table(name="tho_provider")
* @ORM\Entity(repositoryClass="AppBundle\Entity\ProviderRepository")
* @Vich\Uploadable
* @ORM\HasLifecycleCallbacks()
*/
class Provider
{
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="providers")
* @ORM\JoinColumn(name="provider_created_by", referencedColumnName="id")
*/
protected $users;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @Assert\NotBlank()
* @ORM\Column(name="provid_name", type="string", length=255)
*/
private $providName;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* @Vich\UploadableField(mapping="general_image", fileNameProperty="provid_logo")
*
* @var File
*/
private $imageFile;
/**
* @var string
*
* @ORM\Column(name="provid_logo", type="string", length=255)
*/
private $providLogo;
/**
* @var string
*
* @ORM\Column(name="provid_logo_path", type="string", length=255)
*/
private $providLogoPath;
/**
* @var \DateTime
* @Assert\Type("\DateTime")
* @ORM\Column(name="created_time", type="datetime")
*/
private $createdTime;
/**
* @var integer
*
* @ORM\Column(name="provider_created_by", type="integer")
*/
public $providerCreatedBy;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set providName
*
* @param string $providName
* @return Provider
*/
public function setProvidName($providName)
{
$this->providName = $providName;
return $this;
}
/**
* Get providName
*
* @return string
*/
public function getProvidName()
{
return $this->providName;
}
/**
* Set providLogo
*
* @param string $providLogo
* @return Provider
*/
public function setProvidLogo($providLogo)
{
$this->providLogo = $providLogo;
return $this;
}
/**
* Get providLogo
*
* @return string
*/
public function getProvidLogo()
{
return $this->providLogo;
}
/**
* Set providLogoPath
*
* @param string $providLogoPath
* @return Provider
*/
public function setProvidLogoPath($providLogoPath)
{
$this->providLogoPath = $providLogoPath;
return $this;
}
/**
* Get providLogoPath
*
* @return string
*/
public function getProvidLogoPath()
{
return $this->providLogoPath;
}
/**
* Set createdTime
*
* @param \DateTime $createdTime
* @return Provider
*/
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
return $this;
}
/**
* Get createdTime
*
* @return \DateTime
*/
public function getCreatedTime()
{
return $this->createdTime;
}
/**
* Set users
*
* @param \AppBundle\Entity\User $users
* @return Provider
*/
public function setUsers(\AppBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* @return \AppBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
}
/**
* @return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* @ORM\PrePersist
*/
public function setCreatedTimeValue()
{
$this->createdTime = new \DateTime();
}
/**
* Set providerCreatedBy
*
* @param integer $providerCreatedBy
* @return Provider
*/
public function setProviderCreatedBy($providerCreatedBy)
{
$this->providerCreatedBy = $providerCreatedBy;
return $this;
}
/**
* Get providerCreatedBy
*
* @return integer
*/
public function getProviderCreatedBy()
{
return $this->providerCreatedBy;
}
}
USER:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* @ORM\Table(name="tho_user")
* @ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
* @UniqueEntity(fields="email",message = "This email already exist.")
* @UniqueEntity(fields = "username",message = "This username already taken")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* @ORM\OneToMany(targetEntity="Provider", mappedBy="user")
*/
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*@Assert\NotBlank(message="Username is required!")
* @Assert\Length(min=3,minMessage="Minimum 3 characters long.")
* @ORM\Column(name="username", type="string", length=255)
*/
protected $username;
/**
* @var string
*
*
* @ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* @var array
*
* @ORM\Column(name="roles",type="json_array")
*/
private $roles = array();
/**
* @var bool
*
* @ORM\Column(name="is_active",type="boolean")
*/
private $isActive = true;
/**
* @var string
*@Assert\NotBlank()
* @Assert\Email
* @ORM\Column(name="email",type="string", length=255)
*/
private $email;
/**
* @var string
*@Assert\NotBlank()
*
* @ORM\Column(name="first_name",type="string", length=255)
*/
private $firstName;
/**
* @var string
*@Assert\NotBlank()
* @ORM\Column(name="last_name",type="string", length=255)
*/
private $lastName;
/**
* @var string
*
* @ORM\Column(name="iata",type="string", length=255)
*/
private $iata;
/**
* @var string
*
* @ORM\Column(name="job_title",type="string", length=255)
*/
private $jobTitle;
/**
* @var string
*
* @ORM\Column(name="agency_phone",type="string", length=255)
*/
private $agencyPhone;
/**
* @var string
*
* @ORM\Column(name="emergency_mobile",type="string", length=255)
*/
private $emergencyMobile;
/**
* Storing password temporarily
* @Assert\NotBlank()
* @Assert\Length(min=6,minMessage="Minimum 6 characters long.")
* @var string
*/
private $plainPassword;
/**
* Get id
*
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* @param string $password
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
$roles = $this->roles;
$roles[] = 'ROLE_ADMIN';
return array_unique($roles);
}
public function setRoles(array $roles)
{
$this->roles = $roles;
return $this;
}
public function eraseCredentials()
{
$this->setPlainPassword(null);
}
public function getSalt()
{
return null;
}
/**
* @return boolean
*/
public function isIsActive()
{
return $this->isActive;
}
/**
* @param boolean $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* @return bool true if the user's account is non expired, false otherwise
*
* @see AccountExpiredException
*/
public function isAccountNonExpired()
{
return true;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* @return bool true if the user is not locked, false otherwise
*
* @see LockedException
*/
public function isAccountNonLocked()
{
return true;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* @return bool true if the user's credentials are non expired, false otherwise
*
* @see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return true;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* @return bool true if the user is enabled, false otherwise
*
* @see DisabledException
*/
public function isEnabled()
{
return true;
}
/**
* Get isActive
*
* @return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set email
*
* @param string $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* (PHP 5 >= 5.1.0)<br/>
* String representation of object
* @link http://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password
));
}
/**
* (PHP 5 >= 5.1.0)<br/>
* Constructs the object
* @link http://php.net/manual/en/serializable.unserialize.php
* @param string $serialized <p>
* The string representation of the object.
* </p>
* @return void
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password
) = unserialize($serialized);
}
/**
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* @param string $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* @param string $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* @return string
*/
public function getIata()
{
return $this->iata;
}
/**
* @param string $iata
*/
public function setIata($iata)
{
$this->iata = $iata;
}
/**
* @return string
*/
public function getJobTitle()
{
return $this->jobTitle;
}
/**
* @param string $jobTitle
*/
public function setJobTitle($jobTitle)
{
$this->jobTitle = $jobTitle;
}
/**
* @return string
*/
public function getAgencyPhone()
{
return $this->agencyPhone;
}
/**
* @param string $agencyPhone
*/
public function setAgencyPhone($agencyPhone)
{
$this->agencyPhone = $agencyPhone;
}
/**
* @return string
*/
public function getEmergencyMobile()
{
return $this->emergencyMobile;
}
/**
* @param string $emergencyMobile
*/
public function setEmergencyMobile($emergencyMobile)
{
$this->emergencyMobile = $emergencyMobile;
}
/**
* @return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* @param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
}
/**
* Set provider
*
* @param \AppBundle\Entity\Provider $provider
* @return User
*/
public function setProvider(\AppBundle\Entity\Provider $provider = null)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* @return \AppBundle\Entity\Provider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Add providers
*
* @param \AppBundle\Entity\Provider $providers
* @return User
*/
public function addProvider(\AppBundle\Entity\Provider $providers)
{
$this->providers[] = $providers;
return $this;
}
/**
* Remove providers
*
* @param \AppBundle\Entity\Provider $providers
*/
public function removeProvider(\AppBundle\Entity\Provider $providers)
{
$this->providers->removeElement($providers);
}
/**
* Get providers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getProviders()
{
return $this->providers;
}
}
答案 0 :(得分:2)
您的元数据
/**
* @var integer
*
* @ORM\Column(name="provider_created_by", type="integer")
*/
public $providerCreatedBy;
但是你传递的是一个对象(可能是null):
$user = $this->getUser();
/* ... */
$entity->setProviderCreatedBy($user);
并且setter没有类型提示:
public function setProviderCreatedBy($providerCreatedBy)
{
$this->providerCreatedBy = $providerCreatedBy;
return $this;
}
您必须使用$providerCreatedBy
实体更改ManyToOne
到User
的映射。
答案 1 :(得分:1)
检查您的用户是否已登录,$this->getUser()
如果用户是匿名的,则返回null
,我认为您应该从列类型{{更改providerCreatedBy
字段的映射信息1}} integer
与ManyToOne
类的关系..