【发布时间】:2013-11-18 16:30:08
【问题描述】:
我正在尝试在我的 Symfony2 Web 应用程序中创建画廊。
每个帖子可能有也可能没有画廊。我的画廊是文本映射类型,在 Post 实体/类下:
#Post.orm.yml
MyProject\MyProjectBundle\Entity\Post:
type: entity
table: post
repositoryClass: MyProject\MyProjectBundle\Entity\PostRepository
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
# ...
gallery:
type: text
nullable: true
#...
由于画廊中有很多图像,我认为通过我的数据夹具用逗号分隔每个图像是有意义的:
image1.png, image2.jpg, examplename-3rdimage.gif, 4thandfinal.jpg
但是,我希望画廊在查看时输出如下:
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
然后我的控制器调用 Post Entity:
/* PostController.php */
public function postshowAction($id)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MPMPBBundle:Post')->find($id);
$gallery = $em->getRepository('MPMPBBundle:Post')->getGallery();
if (!$entities) {
throw $this->createNotFoundException('Unable to find Post entity.');
}
return $this->render('MPMPBBundle:Post:postshow.html.twig', array(
'entities' => $entities,
'gallery' => $gallery
));
}
您可能已经注意到,我从我的存储库类中引用了函数:getGallery():PostRepository:
/* PostRepository.php */
class PostRepository extends EntityRepository
{
public function getGallery()
{
$postGallery = $this->createQueryBuilder('e')
->select('e.gallery')
->getQuery()
->getResult();
$gallery = array();
foreach ($postGallery as $postGal)
{
$gallery = array_merge(explode(",", $postGal['gallery']), $gallery);
}
foreach ($gallery as &$gal)
{
$gal = trim($gal);
}
return $gallery;
}
}
最后,我的树枝文件:postshow.html.twig,看起来像这样:
{% for gallery in gallery %}
<li>{{ gallery }}</li>
{% endfor %}
澄清一下,我希望实现的是:
# mysite.com/post/post-1
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
# mysite.com/post/post-2
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
每个帖子都显示其各自的图库。
通过上面写的内容,实现的是每个Post 中的所有Gallery 项目都被输出,而我只需要单个帖子的画廊项目:
# mysite.com/post/post-1
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
# mysite.com/post/post-2
<li>image1.png</li>
<li>image2.jpg</li>
<li>examplename-3rdimage.gif</li>
<li>4thandfinal.jpg</li>
<li>image5.png</li>
<li>image11.jpg</li>
<li>examplename-18thimage.gif</li>
<li>22ndandfinal.jpg</li>
【问题讨论】:
标签: php symfony doctrine-orm twig