我想知道如何從此模型中選擇特定的朋友。
模型結構是在這裏:Mongodb odm docrine - 許多自我參考(獲取特定數據)
/**
* @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;
}
得到用戶的朋友,我用這個代碼:
foreach($userSearch->getFriends() as $friend){
$output .= " FriendName: " . $friend->getFirstName() . " - ID: " . $friend->getId() . "<br>";
}
所以,如果我不想讓所有的朋友和環比他們怎樣才能得到特定用戶或用戶(朋友)可以說20歲以上。
EDITED 這裏IM將是集合中的文檔,以便即時尋找一種方法以檢索兩個朋友之一,查詢例如誰是老年人,則x年,而不是用於在客戶端循環。
{
"_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"
}
注:我使用的是模塊ZF2項目(ZF2 + DoctrineOdmMongodb)
值得指出的是,查看API文檔非常方便,因爲常規文檔稍微落後,並且不包含這裏提到的引用表達式方法。 http://www.doctrine-project.org/api/mongodb_odm/1.0/namespace-Doctrine.ODM.MongoDB.Query.html –
我不確定如果我有userRepository,我使用此代碼: '$ this- > DM-> getRepository( '應用程序\型號\用戶') - > createQueryBuilder() - >字段( 'myFriends') - >引用($用戶) - >字段( '的firstName') - >等於( 「德拉甘」) - > getQuery() - > execute()'和結果爲0當我嘗試foreach(循環) –
如果你還沒有實現一個自定義存儲庫類,Doctrine(包括ORM和ODM)將使用一個香草實現(參見:[here](http://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/working-with-objects.html?highlight=repository#custom-repositories))。 Builder和Query類都有一個'debug()'方法,可以用來檢查將發送給Mongo的查詢。這對於直接測試針對Mongo的查詢(例如,在其JS殼中)很有幫助。 – jmikola