Answer the question
In order to leave comments, you need to log in
How to get published posts by tag with active category and user?
I study.
There are Entities: User, Category, Post, Tag
Post - Tag - many-to-many (таблица post_tag)
Category - Post - one-to-many
User - Post - one-to-many
class PostRepository extends ServiceEntityRepository
{
public function findAllActiveByTag(string $slug)
{
return $this->createQueryBuilder('p')
->join('p.tags', 't')->addSelect('t')
->leftJoin('p.user', 'u')->addSelect('u')
->leftJoin('p.category', 'c')->addSelect('c')
->where('t.slug = :slug')->setParameter('slug', $slug)
->andWhere('p.isActive = true')
->andWhere('c.isActive = true')
->orderBy('p.createdAt', 'DESC')
->getQuery()
->getResult();
}
{{ post.title }}
{{ post.category.name }}
{{ post.user.username }}
{% for tag in post.tags %}
{{ tag.name }}
{% endfor %}
Answer the question
In order to leave comments, you need to log in
I don’t know if this is correct or beautiful, I solved the problem like this:
class PostRepository extends ServiceEntityRepository
{
public function findAllActiveByTag(string $slug)
{
$ids = $this->createQueryBuilder('p')
->select('p.id')
->leftJoin('p.tags', 't')
->where('t.slug = :slug')
->setParameter('slug', $slug)
->getQuery()
->getSingleColumnResult();
if ($ids) {
return $this->createQueryBuilder('p')
->leftJoin('p.category', 'c')->addSelect('c')
->leftJoin('p.tags', 't')->addSelect('t')
->leftJoin('p.user', 'u')->addSelect('u')
->where((new Expr())->in('p.id', $ids))
->andWhere('p.isActive = true')
->andWhere('c.isActive = true')
->orderBy('p.createdAt', 'DESC')
->getQuery()
->getResult();
} else {
return [];
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question