MongoDB With Symfony2



我必须在城市级别上提出自动建议,以便我列出与各个国家/地区映射的城市,例如USA => ( "New York", "Dallas", "Los Angeles" .....)

我需要的是使用Symfony2映射方法将其保存在MongoDB中。我搜索了很多,但找不到有关 mongodb 中数组处理的适当帮助或文档。

请解释是否有人在这方面有一些经验。

namespace SPTLUserBundleDocument;
use DoctrineODMMongoDBMappingAnnotations as MongoDB;
/**
* @MongoDBDocument
*/
class City {
/**
 * @MongoDBId
 */
protected $id;
/**
 * @MongoDBString
 */
protected $country;
/**
 * @MongoDBhash
 */
protected $city = array();

/**
 * Get id
 *
 * @return id $id
 */
public function getId()
{
    return $this->id;
}
/**
 * Set country
 *
 * @param string $country
 * @return City
 */
public function setCountry($country)
{
    $this->country = $country;
    return $this;
}
/**
 * Get country
 *
 * @return string $country
 */
public function getCountry()
{
    return $this->country;
}
/**
 * Set city
 *
 * @param hash $city
 * @return City
 */
public function setCity($city)
{
    $this->city = $city;
    return $this;
}
/**
 * Get city
 *
 * @return hash $city
 */
public function getCity()
{
    return $this->city;
}

}

插入用法:

    $dm = $this->get('doctrine_mongodb')->getManager();
    $cities = new City();
    $cities->setCountry("USA");
    $cities->setCity(array("New York", "Dallas", "Los Angeles"));
    $dm->persist($cities);
    $dm->flush();

插入的记录:

{
 "_id": ObjectId("5252b03f6b0f57394e2fb1b5"),
 "country": "USA",
 "city": {
  "0": "New York",
  "1": "Dallas",
  "2": "Los Angeles"  
  } 
}

用于检索的代码:

$repository = $this->get('doctrine_mongodb')->getManager()
    ->getRepository('UserBundle:City');
$cities = $repository->findBy(array("_id"=>'5252b03f6b0f57394e2fb1b5'));
print_r($cities);

但是我无法通过上面的检索代码获取记录.....

如果您需要通过 ObjectId 类型的 id 检索城市你必须从MongoId创建对象,并将你的id作为字符串给出

例:

    $repository = $this->get('doctrine_mongodb')->getManager()
        ->getRepository('UserBundle:City');
    $cityId = new MongoId("5252b03f6b0f57394e2fb1b5");
    $city = $repository->find($cityId);
    var_dump($city);

相关内容

  • 没有找到相关文章

最新更新