从数据库中检索实体字段表单的最佳方法

时间:2013-08-13 12:32:10

标签: symfony doctrine-orm

我有那个实体TwitterPost.php

<?php

namespace FEB\TwitterBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Twitterpost
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="FEB\TwitterBundle\Entity\TwitterpostRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Twitterpost
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titulo", type="string", length=50)
     * @Assert\NotNull(message="Debe escribir un titulo")
     */
    private $titulo;

    /**
     * @var string
     *
     * @ORM\Column(name="tweet", type="string", length=145)
     * @Assert\NotNull(message="Debe escribir un tweet")
     */
    private $tweet;


    /**
     * Many-To-Many, Unidirectional
     *
     * @var ArrayCollection $tags
     *
     * @ORM\ManyToMany(targetEntity="\FEB\TagsBundle\Entity\Tag")
     * @ORM\JoinTable(name="twitterpost_tags",
     *      joinColumns={@ORM\JoinColumn(name="twitterpost_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tag", referencedColumnName="id")}
     * )
     */
    private $tags;


    /**
     * @var string
     *
     * @ORM\Column(name="photo", type="string", length=255, nullable=true)
     */
    private $photo;


    /**
     * @var string
     *
     * @ORM\Column(name="idpost", type="string", length=100)
     */
    private $idpost;

    /**
     * @var string
     *
     * @ORM\Column(name="autor", type="string", length=50)
     */
    private $autor;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;   


    public function __construct()
    {
        $this->setCreated(new \DateTime());
        $this->tags = new ArrayCollection();
    }


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

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

        return $this;
    }

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

    /**
     * Set tweet
     *
     * @param string $tweet
     * @return Twitterpost
     */
    public function setTweet($tweet)
    {
        $this->tweet = $tweet;

        return $this;
    }

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

    /**
     * Set tags
     *
     * @param string $tags
     * @return Twitterpost
     */
    public function setTags($tags)
    {
        $this->tags = $tags;

        return $this;
    }

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

    /**
     * Set photo
     *
     * @param string $photo
     * @return Twitterpost
     */
    public function setPhoto($photo)
    {
        $this->photo = $photo;

        return $this;
    }

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

     /**
     * Set idpost
     *
     * @param string $idpost
     * @return Twitterpost
     */
    public function setIdPost($idpost)
    {
        $this->idpost = $idpost;

        return $this;
    }

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

   /**
     * Set autor
     *
     * @param string $autor
     * @return Twitterpost
     */
    public function setAutor($autor)
    {
        $this->autor = $autor;

        return $this;
    }

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

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Tag
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

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

这一个

/**
 * Tag
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="FEB\TagsBundle\Entity\TagRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Tag
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="tag", type="string", length=255)
     */
    private $tag;

    /**
     * @var string
     *
     * @ORM\Column(name="autor", type="string", length=50)
     */
    private $autor;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    public function __construct()
    {
        $this->setCreated(new \DateTime());
    }   


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

    /**
     * Set tag
     *
     * @param string $tag
     * @return Tag
     */
    public function setTag($tag)
    {
        $this->tag = $tag;

        return $this;
    }

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

    /**
     * Set autor
     *
     * @param string $autor
     * @return Tag
     */
    public function setAutor($autor)
    {
        $this->autor = $autor;

        return $this;
    }

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

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Tag
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

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

这是TwitterPost和Tags之间的多种关系。在我的表单中有一个select字段,它是一个Entity类Tag。

<?php
namespace FEB\TwitterBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class TwitterpostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('titulo')
                ->add('tweet', 'textarea')
                ->add('photo', 'file', array('required' => false))              
                ->add('tags', 'entity', array(
                                                'class' =>    'FEBTagsBundle:tag',
                                                'property' => 'tag',
                                                'empty_value' => 'Selecciona tags',
                                                'multiple' => true));               
    }
    public function getName()
    {
        return 'twitter_form';
    }
}

当我提交数据表格时,在“twitterpost”表格中,数据会正确保存,也会在aux表“twitterpost_tags”中保存。

例如:

twitterpost_id tag_id
1-----------1
1-----------2
2-----------1
2-----------3
The tag table:
id---------tag
1----------tagA
2----------tagB
3----------tagC

当我想显示Twitter邮件的所有数据时,显示标签名称而不是标签ID的最佳方法是什么?

比你先进。

1 个答案:

答案 0 :(得分:0)

我不确定我是否帮助你。要在twitterpost表单中显示所有标记,您已经做了正确的事情:

    ->add('tags', 'entity', array(
          'class' =>    'FEBTagsBundle:tag',
          'property' => 'tag',
          'empty_value' => 'Selecciona tags',
          'multiple' => true
));

这将创建一个多选框,您可以从中选择所有标签。来自the docs

  

<强>属性

     

类型:字符串

     

这是应该用于在HTML元素中将实体显示为文本的属性。如果留空,则实体对象将被强制转换为字符串,因此必须具有__toString()方法。

如果您不想要多选复选框 radiobuttons ,请结帐this part of the documentation


如果您询问如何在不在TwitterpostType内部时输出数据,您可以将它们视为控制器中的对象:

$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findOne($id);

// to get all _tags_ of a post just call the getter:
$tags = $post->getTags();

twig templates

也是如此
{# imagine you have all posts in a variable called 'posts' #}
{% for post in posts %}
     <h1>{{ post.titulo }}</h1>
     <div class="tags">
         {% for tag in posts.tags %}
         {{ tag.tag }}
         {% endfor %}
     </div>
{% endfor %}

编辑:

对于本机SQL / DQL查询,您需要a custom repository class。在那里,您可以存储自己的查询:

class TwitterpostRepository extends EntityRepository
{
    public function findAllOrderedByName()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT p FROM TwitterBundle:Twitterpost p ORDER BY p.name ASC'
            )
            ->getResult();
    }
}

然后你可以在控制器中使用它:

$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findAllOrderedByName();