2015-08-11 3 views
0

Я новичок в Symfony2 и Doctrine, я немного застрял. Ошибка при сохранении в базе данных.Доктрина: Symfony 2 иностранный ключ null перед флешем

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]: Integrity нарушение ограничения: 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(), 
    ); 
} 

У меня есть сущности, ПРОВАЙДЕР и ПОЛЬЗОВАТЕЛЬ. Пользователь может создать свой собственный провайдер и поставщик услуг, принадлежащий одному пользователю. От одного до многих отношений.

<?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 &gt;= 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 &gt;= 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; 
     } 
    } 

ответ

1

Проверьте, если ваш пользователь был войти в систему, $this->getUser() возвращает null, если пользователь является анонимным, и я думаю, вы должны изменить свои данные отображения для providerCreatedBy поля от типа столбца integer для ManyToOne отношений с User класса ..

+0

Спасибо, помощник, работа с картинкой. –

2

Ваши метаданные

/** 
* @var integer 
* 
* @ORM\Column(name="provider_created_by", type="integer") 
*/ 
public $providerCreatedBy; 

но вы передаете объект (возможно, пустой):

$user = $this->getUser(); 
/* ... */ 
$entity->setProviderCreatedBy($user); 

И сеттер не имеет тип подсказки:

public function setProviderCreatedBy($providerCreatedBy) 
{ 
    $this->providerCreatedBy = $providerCreatedBy; 

    return $this; 
} 

Вы должны изменить свое отображение $providerCreatedBy в ManyToOne с User лица ,

+0

Спасибо, я проверяю пользователя. Он вошел в систему. Все работает, как только я изменяю отображение :) Большое спасибо. –

Смежные вопросы