我是 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”不能为空
我的表单仅获取提供程序名称输入和徽标,其余的是我在控制器中处理,包括在刷新后、刷新命令显示值之前获取 null 的provider_created_by。
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(),
);
}
我有实体、提供者和用户。 用户可以创建多个提供者,并且提供者只属于一个用户。一对多的关系。
<?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;
}
}
用户:
<?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;
}
}
检查您的用户是否已登录,如果用户是匿名,
$this->getUser()
返回null
,我也认为您应该更改providerCreatedBy
字段的映射信息,从列类型integer
更改为ManyToOne
与的关系User
班级..
您的元数据是
/**
* @var integer
*
* @ORM\Column(name="provider_created_by", type="integer")
*/
public $providerCreatedBy;
但是你正在传递一个对象(可能为空):
$user = $this->getUser();
/* ... */
$entity->setProviderCreatedBy($user);
并且 setter 没有类型提示:
public function setProviderCreatedBy($providerCreatedBy)
{
$this->providerCreatedBy = $providerCreatedBy;
return $this;
}
您必须使用
$providerCreatedBy
实体将 ManyToOne
的映射更改为 User
。