我有两个实体帖子和标签这个实体有关系ManyToMany,很多帖子都有很多标签,很多标签都有很多帖子,并且有实体类别我很多发布一个类别我需要创建动作查找类别的帖子并找到帖子标签
class Tag
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=100)
*/
protected $hashTag;
/**
* @Gedmo\Slug(fields={"hashTag"})
* @ORM\Column(type="string", length=12)
*/
protected $hashSlug;
/**
* @ORM\ManyToMany(targetEntity="Post", inversedBy="tag")
* @ORM\JoinColumn(name="post_id", referencedColumnName="id")
*/
protected $post;
类别:
class Category
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\Column(name="title", type="string", length=64)
*/
private $title;
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
protected $posts;
发布
class Post
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", nullable=true)
*/
private $title;
/**
* @ORM\ManyToMany(targetEntity="Tag", mappedBy="post")
* @ORM\JoinTable(name="posts_tag")
*/
protected $tag;
和我在我的操作字段hashTag中发布的模板:
<p class="lead">
Category:<a href="{{ path('get_posts_for_category', {'category': post.category.title}) }}">{{ post.category }}</a>
</p>
{% for tags in post.tag %}
<a class="btn btn-primary" href="{{ path('get_posts_for_tags', {'tags': tags }) }}">{{ tags }} <span class="glyphicon glyphicon-chevron-right"></span></a>
{% endfor %}
public function indexAction(Request $request, $tag)
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('PillsBundle:Post')
->getPostByTag($tags);
结束这是功能:
public function getPostByTag($tag)
{
$date = new \DateTime;
$qb = $this->getEntityManager()->createQueryBuilder('p');
$qb
->select('p')
->from('PillsBundle:Post', 'p')
->getQuery();
$query = $qb->getQuery();
$results = $query->getResult();
// dump($results);exit; => I have all posts
// And I dont know what to do next, help
}
和类别:
public function indexAction(Request $request, $category)
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('PillsBundle:Post')
->getPostByCategory($category);
public function getPostByCategory($category)
{
$date = new \DateTime;
$qb = $this->getEntityManager()->createQueryBuilder('p');
$qb ->select('p')
->from('PillsBundle:Post', 'p')
->join('p.category', 'c')
->where('c = :category')
->setParameter('category', $category)
->getQuery();
$query = $qb->getQuery();
$results = $query->getResult();
return $results;
}
如果我使用这个QueryBuilder,我发布的内容(现在我发布了categoty.slug)需要这个函数吗? 请帮忙
答案 0 :(得分:0)
您必须将标记传递给查询,以便......
public function getPostByTag($tag)
{
$date = new \DateTime;
$qb = $this->getEntityManager()->createQueryBuilder('p');
$qb
->select('p')
->from('PillsBundle:Post', 'p')
->join('p.tag', 't')
->where('t = :tag')
->setParameter('tag', $tag)
->getQuery();
$query = $qb->getQuery();
$results = $query->getResult();
return $results;
}
应该像这样工作,但是你应该改变你的名字,这很令人困惑,如果你只发送一个标签,你必须称它为标签,而不是标签。总是当你有许多属于实体的标签时,你必须称之为标签,复数