0

I have the follow problem with nested finding of collection element:

class User
{
    /*
     * @MongoDB\Id(strategy="auto")
     */
    protected $id;
}

class Network
{
    /*
     * @MongoDB\ReferenceOne(targetDocument="User")
     */
    protected $owner;
}

class Connection
{
    /*
     * @MongoDB\ReferenceOne(targetDocument="Network")
     */
    protected $network;
}

How I can find all user own network connections (by user id) in Doctrine ODM Query builder? P.S. Native mongodb query will accept too.

4

3 回答 3

1
public function findByUserId($userId)
{
    return $this->dm->getRepository(Connection::class)->findBy([
        'network.owner.$id' => new MongoId($userId),
    ]);
}
于 2013-11-13T16:22:04.447 回答
0

不幸的是,您不能直接通过引用文档的字段进行查询,最好由关系数据库处理。在 MongoDB 中,这当然是可能的,但需要多次查询:首先你找到用户所属的网络,然后你应该找到网络的连接。

当然,获取网络标识符列表进行连接查询就足够了。这可以在查询生成器的帮助下轻松完成:

$networkQb = $this->dm->getRepository(Network::class)->createQueryBuilder();
$networkQb->field('owner.$id')->equals($userId);
$networkQb->select('_id'); // Limit results to the ID of the network only
$networkQb->hydrate(false); // Don't return Network objects but only plain array

$networkResults = $networkQb->getQuery()->toArray();
$networkIdList = array_map(function($result) { return $result['_id']; }, $networkResults); // This converts array(array("_id" => "1234"), array("_id" => "5678")) to array("1234","5678")

// Then we'll make the actual query for the connections, based on the id list of the networks
$connectionQb = $this->dm->getRepository(Connection::class)->createQueryBuilder();
$connectionQb->field('network.$id')->in($networkIdList);

$connections = $connectionQb->getQuery()->toArray();

只要每个用户只有几个网络,这种查询还是比较快的。

于 2014-01-30T09:35:14.300 回答
0

您必须对@MongoDB\ReferenceOne使用Query Builder的references()方法,例如https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html

$user = $dm->getRepository('User')->findOneById($userId);

$queryBuilder = $dm->getRepository('Network')->createQueryBuilder()
                   ->field('owner')->references($user);

$ownNetworkConnections = $queryBuilder->getQuery()->execute();


PS:使用includesReferenceTo()一个@MongoDB\ReferenceMany

于 2015-10-09T13:17:46.980 回答