duankuaiwang2706 2012-09-03 07:53
浏览 67
已采纳

Mongodb odm docrine - 自我参考多对多(获取具体数据)

I want to know how can I select specific friend from this model.
The model structure is here:

    /**
     * @MongoDB\ReferenceMany(targetDocument="Users", mappedBy="myFriends")
     */
    public $friendsWithMe;

    /**
     * @MongoDB\ReferenceMany(targetDocument="Users", inversedBy="friendsWithMe")
     */
    public $myFriends;

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

    /**
     * Add friend
     * @param Users $user
     */
    public function addFriend(Users $user) {
        $user->friendsWithMe[] = $this;
        $this->myFriends[] = $user;
    }

    /**
     * Get friends
     * @return Array $myFriends
     */
    public function getFriends() {
        return $this->myFriends;
    }

To get user friends I use this code:

foreach($userSearch->getFriends() as $friend){
    $output .= "&nbsp;FriendName: " . $friend->getFirstName() . " - ID: " . $friend->getId() . "<br>";
}

So if I don't want to get all friend and loop over them how can I get specific users or user(friend/s) lets say older then 20 years.

EDITED Here im adding the document that is in the collection so im looking for a way to retrive one of the two friend with query for example who is older then x years instead of for loop on client side.

{
   "_id": ObjectId("503f3028e71a38840d000000"),
   "birthdate": ISODate("2012-08-30T09: 19: 36.0Z"),
   "email": "mail",
   "firstName": "asd",
   "myFriends": {
     "0": {
       "$ref": "Users",
       "$id": ObjectId("503e1683921da8c80b000002"),
       "$db": "testing" 
    },
     "1": {
       "$ref": "Users",
       "$id": ObjectId("503e0a8ee71a38080b000001"),
       "$db": "testing" 
    } 
  },
   "password": "123",
   "role": {
     "$ref": "UserRoles",
     "$id": ObjectId("50486ba1e71a384c15000000"),
     "$db": "testing" 
  },
   "username": "gizmo" 
}

Note: I'm using with module for ZF2 project (ZF2 + DoctrineOdmMongodb)

  • 写回答

2条回答 默认 最新

  • duan19805 2012-09-04 01:34
    关注

    Assuming you have a managed user document $user and an instance of UserRepository $userRepository.

    $users = $userRepository->createQueryBuilder()->field('myFriends')->includesReferenceTo($user)->field('age')->gt(20)->getQuery()->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?