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 .= " 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)
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();