dongwen2896 2015-09-15 19:32
浏览 30

学说2 - 如何在没有特定文章的情况下获取类别

Iam learning Doctrine. I have two entities Article and Category in many to many relationship and iam trying to get all categories where isnt specific article.

ArticleEntity:

class Article extends BaseEntity
{

    use Identifier;

    /**
     * @ORM\Column(type="string", nullable = false, unique=TRUE)
     * @var string
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="articles")
     * @ORM\JoinTable(name="article_categories")
     */
    private $categories;

    public function getCategories()
    {
       return $this->categories;
    }


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

And CategoryEntity:

    class Category extends BaseEntity
{

    use Identifier;

    /**
     * @ORM\Column(type="string", nullable = false, unique=true)
     * @var string
     */
    private $title;


    /**
     * @ORM\Column(type="string",nullable=false,unique=true)
     * @var sting
     */
    private $slug;

    /**
     * @ORM\ManyToMany(targetEntity="Article", mappedBy="categories")
     */
    private $articles;



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

And i am trying to get all categories without specific article. In pure MySQL id would be something like this:

SELECT * FROM category LEFT JOIN article_categories ON category.id = article_categories.category_id WHERE article_categories.article_id <> 1(for example) AND article_id IS NOT NULL

And the only solution i could create in my CategoryRepository is this one.

public function findWithoutArticle($article_id)
{
    $articleCat = $this->em->find(Article::getClassName(), $article_id);
    $qb = $this->em->createQueryBuilder();
    $qb->select('c')
        ->from(Category::getClassName(), 'c')
        ->where('c.id NOT IN (:article_id)')
        ->setParameter('article_id', $articleCat->getCategories()->toArray());
    return $qb->getQuery()->getResult();
}

And this doesnt look right. Is there any better "Doctrine way" practice?

  • 写回答

2条回答 默认 最新

  • douchun3680 2015-09-16 06:38
    关注

    How about this one?

    $qb = $this->em->createQueryBuilder();
    $qb->select('c');
    $qb->from('Category', 'c');
    $qb->leftJoin('c.articles', 'a');
    $qb->where($qb->expr()->neq('a.article_id', '?1'));
    $qb->setParameter(1, $article_id);
    $categories = $qb->getQuery()->getResult();
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度