/** * Transform the value in a MongoDBRef if needed * @param $attr * @param $value * @return mixed */ protected function _val($attr, $value) { $reference = \Rocketr\Schema\Reference::get($this->get_collection_name(), $attr); $collection = \Rocketr\Schema\HasCollection::get($this->get_collection_name(), $attr); if ($reference xor $collection) { $ref_attr = \Rocketr\Schema\Map::on($this->get_collection_name(), $attr); $_id = is_array($value) && isset($value[$ref_attr]) || is_object($value) && $value->{$ref_attr} ? is_array($value) ? $value[$ref_attr] : $value->{$ref_attr} : $value; $target = $reference ? $reference : $collection; $_id = $ref_attr == '_id' && \MongoId::isValid($_id) ? new \MongoId($_id) : $_id; return \MongoDBRef::create($target, $_id); } else { return $value; } }
<?php require '../src/Rocketr/Autoloader.php'; \Rocketr\Autoloader::register(); $Knot = new Rocketr\Engine(); $Knot->connexion('mongodb://127.0.0.1:27017')->database('default'); $map = ['reference' => ['books' => ['author' => 'authors', 'writer' => 'authors']], 'has_collection' => ['libraries' => ['archives' => 'books', 'books' => 'books'], 'shelves' => ['books' => 'books'], 'authors' => ['beloved_places' => 'cities']]]; \Rocketr\Schema\Map::load($map); //\Rocketr\Schema\Reference::add('books', ['author' => 'authors']); echo 'One To Many Relation --- <br />'; echo 'From the descendant --- <br />'; $B = $Knot->find('books')->where('author.name = "Terry Pratchett"')->one(); echo "<pre>"; echo print_r($B, true); echo "</pre>"; echo 'From the ascendant --- <br />'; $A = $Knot->find('authors')->having('books')->where('title = "Quand le diable était jeune"')->as('author')->one(); echo "<pre>"; echo print_r($A, true); echo "</pre>";
private function _run_hascollection_queries($criterion, $sub_queries, $val) { $ref_attr = array_shift($sub_queries); $target = \Rocketr\Schema\HasCollection::get($this->get_collection_name(), $ref_attr); $condition = $this->_stringify_condition($criterion, $sub_queries, $val); $on = \Rocketr\Schema\Map::on($this->get_collection_name(), $ref_attr); $result = $this->_run_sub_query($target, $condition, $on); return $this->_make_references_ids($result, $on, $ref_attr); }