AnkitJ AnkitJ - 1 year ago 86
PHP Question

Find method on embedded document is returning null in symfony mongo



I am new to symfony and creating project using mongodb as database. I am using embedded document in order to achieve multi-level database. Below are two document files I am using:
Documents:

namespace AppBundle\Document;

/**
* @MongoDB\Document()
*/
class State
{
/**
* @MongoDB\Id()
*/
protected $id;

/**
* @MongoDB\Field(type="string")
*/
protected $name;

/**
* @MongoDB\Field(type="string")
*/
protected $code;

/**
* @MongoDB\EmbedMany(targetDocument="City")
*/
protected $cities = array();

/**
* State constructor.
*/
public function __construct()
{
$this->cities = new ArrayCollection();
}

/**
* @return mixed
*/
public function getId()
{
return $this->id;
}

/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}

/**
* @return mixed
*/
public function getName()
{
return $this->name;
}

/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}

/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}

/**
* @param mixed $code
*/
public function setCode($code)
{
$this->code = $code;
}

/**
* @return City[]
*/
public function getCities()
{
return $this->cities;
}

/**
* @param City $city
*/
public function addCities(City $city)
{
$this->cities[] = $city;
}
}

/**
* @MongoDB\EmbeddedDocument()
*/
class City
{
/**
* @MongoDB\Id
*/
protected $id;

/**
* @MongoDB\Field(type="string")
*/
protected $name;

/**
* @return mixed
*/
public function getId()
{
return $this->id;
}

/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}

/**
* @return mixed
*/
public function getName()
{
return $this->name;
}

/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}

}


I am properly able to add data to database and preview of it displayed below:


{
"_id" : ObjectId("59783f79d6faef0dc13cc8ce"),
"name" : "New South Wales",
"code" : "NSW",
"cities" : [
{
"_id" : ObjectId("59783f79d6faef0dc13cc8cf"),
"name" : "Sydney"
}
]
}


And now I am getting data using method "find()" with it's id:


$city = $this->get('doctrine_mongodb')
->getManager()
->getRepository('AppBundle:City')
->find("59783f79d6faef0dc13cc8cf");


So, Problem here is:



I am receiving null in $city. How can I get details of city like name?

Answer Source

You have mapped City as an embedded document thus it can't exist without its parent document. The only way you can get it is fetching the State and then iterating through $state->getCities(). If you need to query for cities, you need references so City would become a first class document with its own collection Mongo can scan.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download