symfony2:将对象存储在数据库中

时间:2012-03-11 20:48:44

标签: doctrine symfony

当我尝试执行以下操作时,我收到此错误:

  

SQLSTATE [23000]:完整性约束违规:1048列'category_id'不能为空(500内部服务器错误)

正如您在操作中看到的那样我设置了字段category_id(setCategoryId()),那么错误的原因是什么?

注意:正如您所看到的,我正在尝试在数据库中保存一个提案(propuesta)和与之关联的标签。

public function savePropuestaAction() {

    $em = $this->get('doctrine.orm.entity_manager');
    $propuesta = new Propuestas();

    //retrieve the values inserted in the form.    
    $form = $this->getRequest()->request->get('form');
    $propuestaContent = $form['propuesta'];
    $propuestaCategory = $form['Categoría'][0];     

    $propuesta->setTitulo('$propuestaCategory');
    $propuesta->setContenido($propuestaContent);
    $propuesta->setCategoryId(1);

    //retrieve the tags inserted in the form...
    $tags = array();
    foreach($form as $key => $field)
    {
      if(substr($key, 0, 3) == 'tag')
      {
        $tagsName[] = $field;
      }
    }

    // ...and then store them and associate them to the proposal.
    if(count($tagsName))
    {                  
      foreach($tagsName as $tagName)
      { 
        $tag = new TagPropuesta();
        $tag->setName($tagName);
        $em->persist($tag);
        $em->flush();

        $propuesta->addTagPropuesta($tag);
        $em->persist($propuesta);
        $em->flush();
      }
    }              

    return new Response();
}

编辑:经过几次回答我尝试过更换线路

$propuesta->setCategoryId(1);

$repository = $this->getDoctrine()->getRepository('JanderJanderBundle:PropuestasCategory');
$category = $repository->find(1);
//die(get_class($category)); 
$propuesta->setCategory($category);

但错误信息是相同的..

这里你还有.yml文件和实体Propuesta(我根本没有修改Propuesta类,我只使用generate:entities任务生成它):

Jander\JanderBundle\Entity\Propuestas:
  type: entity
  table: propuestas
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
    category_id:
      type: integer
      nullable: true
    user_id:
      type: integer
      nullable: true
    titulo:
      type: string
      length: 230
      fixed: false
    contenido:
      type: string
      length: 230
      fixed: false
    tema:
      type: string
      length: 40
      fixed: false
      nullable: true
    eliminado:
      type: boolean
      nullable: true
    created:
      type: date
      gedmo:
        timestampable:
          on: create
    votes_up:
      type: integer
      nullable: true
    votes_down:
      type: integer
      nullable: true
  manyToOne:
    category:
      targetEntity: PropuestasCategory
      inversedBy: propuestas
      joinColumn:
        name: category_id
        referencedColumnName: id  
    usuario:
      targetEntity: Usuario
      inversedBy: propuestas
      joinColumn:
        name: user_id
        referencedColumnName: id
  manyToMany:
    tags:
      targetEntity: TagPropuesta
      inversedBy: propuestas    
  lifecycleCallbacks: {  }



<?php

namespace Jander\JanderBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Jander\JanderBundle\Entity\Propuestas
 */
class Propuestas
{
    /**
     * @var integer $id
     */
    private $id;

    /**
     * @var string $contenido
     */
    private $contenido;

    /**
     * @var string $tema
     */
    private $tema;

    /**
     * @var boolean $eliminado
     */
    private $eliminado;

    /**
     * @var date $created
     */
    private $created;

    /**
     * @var integer $votes
     */
    private $votes;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set contenido
     *
     * @param string $contenido
     */
    public function setContenido($contenido)
    {
        $this->contenido = $contenido;
    }

    /**
     * Get contenido
     *
     * @return string 
     */
    public function getContenido()
    {
        return $this->contenido;
    }

    /**
     * Set tema
     *
     * @param string $tema
     */
    public function setTema($tema)
    {
        $this->tema = $tema;
    }

    /**
     * Get tema
     *
     * @return string 
     */
    public function getTema()
    {
        return $this->tema;
    }

    /**
     * Set eliminado
     *
     * @param boolean $eliminado
     */
    public function setEliminado($eliminado)
    {
        $this->eliminado = $eliminado;
    }

    /**
     * Get eliminado
     *
     * @return boolean 
     */
    public function getEliminado()
    {
        return $this->eliminado;
    }

    /**
     * Set created
     *
     * @param date $created
     */
    public function setCreated($created)
    {
        $this->created = $created;
    }

    /**
     * Get created
     *
     * @return date 
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set votes
     *
     * @param integer $votes
     */
    public function setVotes($votes)
    {
        $this->votes = $votes;
    }

    /**
     * Get votes
     *
     * @return integer 
     */
    public function getVotes()
    {
        return $this->votes;
    }
    /**
     * @var integer $category_id
     */
    private $category_id;

    /**
     * @var Jander\JanderBundle\Entity\PropuestasCategory
     */
    private $category;


    /**
     * Set category_id
     *
     * @param integer $categoryId
     */
    public function setCategoryId($categoryId)
    {
        $this->category_id = $categoryId;
    }

    /**
     * Get category_id
     *
     * @return integer 
     */
    public function getCategoryId()
    {
        return $this->category_id;
    }

    /**
     * Set category
     *
     * @param Jander\JanderBundle\Entity\PropuestasCategory $category
     */
    public function setCategory(\Jander\JanderBundle\Entity\PropuestasCategory $category)
    {
        $this->category = $category;
    }

    /**
     * Get category
     *
     * @return Jander\JanderBundle\Entity\PropuestasCategory 
     */
    public function getCategory()
    {
        return $this->category;
    }
    /**
     * @var Jander\JanderBundle\Entity\TagPropuesta
     */
    private $tags;

    public function __construct()
    {
        $this->tags = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add tags
     *
     * @param Jander\JanderBundle\Entity\TagPropuesta $tags
     */
    public function addTagPropuesta(\Jander\JanderBundle\Entity\TagPropuesta $tags)
    {
        $this->tags[] = $tags;
    }

    /**
     * Get tags
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getTags()
    {
        return $this->tags;
    }
    /**
     * @var integer $user_id
     */
    private $user_id;

    /**
     * @var Jander\JanderBundle\Entity\Usuario
     */
    private $usuario;


    /**
     * Set user_id
     *
     * @param integer $userId
     */
    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    /**
     * Get user_id
     *
     * @return integer 
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    /**
     * Set usuario
     *
     * @param Jander\JanderBundle\Entity\Usuario $usuario
     */
    public function setUsuario(\Jander\JanderBundle\Entity\Usuario $usuario)
    {
        $this->usuario = $usuario;
    }

    /**
     * Get usuario
     *
     * @return Jander\JanderBundle\Entity\Usuario 
     */
    public function getUsuario()
    {
        if($this->usuario == null)
        {
            return "anonimo";  
        }else{
            return $this->usuario;
        }

    }
    /**
     * @var integer $jander
     */
    private $jander;


    /**
     * Set jander
     *
     * @param integer $jander
     */
    public function setJander($jander)
    {
        $this->jander = $jander;
    }

    /**
     * Get jander
     *
     * @return integer 
     */
    public function getJander()
    {
        return $this->jander;
    }
    /**
     * @var integer $votes_up
     */
    private $votes_up;

    /**
     * @var integer $votes_down
     */
    private $votes_down;


    /**
     * Set votes_up
     *
     * @param integer $votesUp
     */
    public function setVotesUp($votesUp)
    {
        $this->votes_up = $votesUp;
    }

    /**
     * Get votes_up
     *
     * @return integer 
     */
    public function getVotesUp()
    {
        if($this->votes_up == null)
        {
          return 0;
        }
        else
        {
          return $this->votes_up;
        }    
    }

    /**
     * Set votes_down
     *
     * @param integer $votesDown
     */
    public function setVotesDown($votesDown)
    {
        $this->votes_down = $votesDown;
    }

    /**
     * Get votes_down
     *
     * @return integer 
     */
    public function getVotesDown()
    {
        if($this->votes_down == null)
        {
          return 0;
        }
        else
        {
          return $this->votes_down;
        }    


    }

    public function getTotalVotes()
    {
        return ($this->getVotesDown()+$this->getVotesUp());
    }
    /**
     * @var string $titulo
     */
    private $titulo;


    /**
     * Set titulo
     *
     * @param string $titulo
     */
    public function setTitulo($titulo)
    {
        $this->titulo = $titulo;
    }

    /**
     * Get titulo
     *
     * @return string 
     */
    public function getTitulo()
    {
        return $this->titulo;
    }
}

哈维

2 个答案:

答案 0 :(得分:2)

我认为你的db表名为'propuesta'有一个foreignkey category_id,对吧?然后在你的实体中必须有一个字段类别而不是category_id,它的set和get函数是setCategory()和getCategory(),而不是setCategoryId()。对于foreignkey相关字段必须具有预期的对象。所以在你的情况下

$category=$em->getDoctrine()->getEnitityManager()->getRepository('YourBundleName:Category')->find($id);
$propuesta->setCategory($category);//here category is an object.

所以首先检查你的propuesta实体及其yml文件。

<强>更新

1. Change your yml like this

    Jander\JanderBundle\Entity\Propuestas:
      type: entity
      table: propuestas
      fields:
        id:
          id: true
          type: integer
          unsigned: false
          nullable: false
          generator:
            strategy: IDENTITY
        user_id:
          type: integer
          nullable: true
        titulo:
          type: string
          length: 230
          fixed: false
        contenido:
          type: string
          length: 230
          fixed: false
        tema:
          type: string
          length: 40
          fixed: false
          nullable: true
        eliminado:
          type: boolean
          nullable: true
        created:
          type: date
          gedmo:
            timestampable:
              on: create
        votes_up:
          type: integer
          nullable: true
        votes_down:
          type: integer
          nullable: true
      manyToOne:
        category:
          targetEntity: PropuestasCategory
          inversedBy: propuestas
          joinColumn:
            name: category_id
            referencedColumnName: id  
        usuario:
          targetEntity: Usuario
          inversedBy: propuestas
          joinColumn:
            name: user_id
            referencedColumnName: id
      manyToMany:
        tags:
          targetEntity: TagPropuesta
          inversedBy: propuestas    
      lifecycleCallbacks: {  }

您不需要在yml文件中指定category_id,只需指定关系。

  1. 同时更改您的实体文件

    删除字段categoryid及其setCategoryId()和getCategoryId()函数。

  2. 您必须更改其他表的所有yml文件并提供上述关系。还要更改其实体文件。

  3. 只需了解如何编写yml文件及其关系,然后使用symfony2的generate:enitites命令。

    如果您不知道如何编写yml及其实体另一个好的方法是反向过程 1.首先创建数据库及其表,在msql中根据需要提供其外键关系。

    1. 在项目的parameters.ini文件中设置数据库连接。(希望你知道,只需提供dbname,username,password(如果有的话))。

    2. 删除res / config / doctrine /和实体文件中的所有yml文件。

    3. 4.打开你的终端只需提供以下命令。以下命令会自动生成所有实体文件和yml文件,并在数据库中指定正确的关系。

      a).php app / console doctrine:mapping:convert yml ./src/Acme/BlogBu​​ndle/Resources/config/doctrine --from-database --force // Acme / BlogBu​​ndle / is namespace

      Symfony2从数据库生成实体
       b).php app / console doctrine:mapping:import AcmeBlogBu​​ndle yml // AcmeBlogBu​​ndle是包名  c).php app / console doctrine:generate:entities AcmeBlogBu​​ndle

      如果您有任何疑问,请参阅此链接Click here

      希望这有助于你

答案 1 :(得分:0)

需要思考物体,而不是ids';

$category = $em=>getReference('Category',1);
$propuesta->setCategory($category);

我假设您确实定义了propuesta和category之间的关系。