【问题标题】:Symfony 2 Doctrine ODM with referenceSymfony 2 Doctrine ODM 参考
【发布时间】:2013-11-19 15:04:51
【问题描述】:

所以我有以下两个文件:

壁纸

/**
 * @MongoDB\Document(
 *    collection="wallpapers",
 *    repositoryClass="Application\Bundle\DefaultBundle\Repository\WallpaperRepository"
 * )
 */
class Wallpaper
{
    /**
     * @MongoDB\Id(strategy="auto")
     * @var string $id
     */
    private $id;

    /**
     * @var ArrayCollection
     *
     * @MongoDB\ReferenceMany(
     *     targetDocument="Category"
     * )
     *
     * 
     */
    private $categories;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }
}

类别:

/**
 * @MongoDB\Document(collection="categories")
 */
class Category
{

    /**
     * @MongoDB\Id(strategy="auto")
     * @var string $id
     */
    private $id;

    /**
     * @MongoDB\Field(type="boolean")
     *
     * @var bool $published
     */
    private $published;
}

我需要选择所有只包含已发布类别的壁纸... 我尝试了很多解决方案,都是通过 Google 搜索找到的。但仍然没有找到我的问题的解决方案...

这是我的查询:

$wallpapers = $this->createQueryBuilder('ApplicationDefaultBundle:Wallpaper')
            ->field('categories.published')->equals(true)
            ->getQuery()
            ->execute()

但它不起作用:(

有什么建议吗?

【问题讨论】:

    标签: php mongodb symfony doctrine-orm doctrine-odm


    【解决方案1】:

    在关系数据库中,您可以使用 Join 来实现,但在 mongodb 中,您可以:


    去规范化您在墙纸文档中引用的类别:

    /**
     * @MongoDB\EmbedMany(targetDocument="Category")
     */
    private $categories;
    

    (注意 EmbedMany)

    这样您的查询将起作用(但类别将在每个壁纸中重复)


    或者做这个简单的技巧(如果类别的数量不是太多):

    //Get all the ids of the published categories:
    $categories = $this->createQueryBuilder('ApplicationDefaultBundle:Category')
                ->field('published')->equals(true)
                ->getQuery()
                ->execute()
    $categoriesIds = array();
    foreach($categories as $c) {
        $categoriesIds[] = $c->getId();
    }
    
    //Get the wallpapers for that categories:
    $wallpapers = $this->createQueryBuilder('ApplicationDefaultBundle:Wallpaper')
                ->field('categories.$id')->in($categories)
                ->getQuery()
                ->execute()
    

    如果发布的类别只有 100-200 这个技巧是可以的。

    【讨论】:

    • 我将通过仅选择 _id 字段而不是对结果进行水合来进一步优化类别查询。只需将->fields(array('_id'))->hydrate(false) 添加到第一个查询生成器,而不是$c->getId() 使用$c['_id']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2017-04-29
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多