From 3d6192a5019f52858fa22ea3640f2a0fac05599b Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 21 Nov 2013 09:52:03 +0000 Subject: [PATCH 1/9] Readme updated to show belongsToMany relationship availability --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index aebec2951..005f9ba73 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ Supported relations are: - hasOne - hasMany - belongsTo + - belongsToMany Example: From da047546326e303dc979edeedea6c226d822b8d9 Mon Sep 17 00:00:00 2001 From: Jens Segers Date: Wed, 20 Nov 2013 22:35:25 +0100 Subject: [PATCH 2/9] Slimming down the BelongsToMany class --- .../Mongodb/Relations/BelongsToMany.php | 188 ++-------- tests/RelationsTest.php | 334 +++++++++--------- 2 files changed, 187 insertions(+), 335 deletions(-) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php index a0aff091e..d09967c05 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php @@ -1,4 +1,5 @@ getSelectColumns($columns); - - $models = $this->query->addSelect($select)->getModels(); - - // If we actually found models we will also eager load any relationships that - // have been specified as needing to be eager loaded. This will solve the - // n + 1 query problem for the developer and also increase performance. - if (count($models) > 0) - { - $models = $this->query->eagerLoadRelations($models); - } - - return $this->related->newCollection($models); + // Do nothing } - + /** * Set the select clause for the relation query. * @@ -42,26 +28,6 @@ protected function getSelectColumns(array $columns = array('*')) return $columns; } - /** - * Get a paginator for the "select" statement. - * - * @param int $perPage - * @param array $columns - * @return \Illuminate\Pagination\Paginator - */ - public function paginate($perPage = null, $columns = array('*')) - { - $this->query->addSelect($this->getSelectColumns($columns)); - - // When paginating results, we need to add the pivot columns to the query and - // then hydrate into the pivot objects once the results have been gathered - // from the database since this isn't performed by the Eloquent builder. - $pager = $this->query->paginate($perPage, $columns); - - return $pager; - } - - /** * Set the base constraints on the relation query. * @@ -69,7 +35,7 @@ public function paginate($perPage = null, $columns = array('*')) */ public function addConstraints() { - if (static::$constraints) + if (static::$constraints) { // Make sure that the primary key of the parent // is in the relationship array of keys @@ -77,55 +43,6 @@ public function addConstraints() } } - /** - * Set the constraints for an eager load of the relation. - * - * @param array $models - * @return void - */ - public function addEagerConstraints(array $models) - { - $this->query->whereIn($this->getForeignKey(), $this->getKeys($models)); - } - - /** - * Save a new model and attach it to the parent model. - * - * @param \Illuminate\Database\Eloquent\Model $model - * @param array $joining - * @param bool $touch - * @return \Illuminate\Database\Eloquent\Model - */ - public function save(Model $model, array $joining = array(), $touch = true) - { - $model->save(array('touch' => false)); - - $this->attach($model->getKey(), $joining, $touch); - - return $model; - } - - /** - * Create a new instance of the related model. - * - * @param array $attributes - * @param array $joining - * @param bool $touch - * @return \Illuminate\Database\Eloquent\Model - */ - public function create(array $attributes, array $joining = array(), $touch = true) - { - $instance = $this->related->newInstance($attributes); - - // Save the new instance before we attach it to other models - $instance->save(array('touch' => false)); - - // Attach to the parent instance - $this->attach($instance->_id, $attributes, $touch); - - return $instance; - } - /** * Sync the intermediate tables with a list of IDs. * @@ -139,13 +56,13 @@ public function sync(array $ids, $detaching = true) // in this joining table. We'll spin through the given IDs, checking to see // if they exist in the array of current ones, and if not we will insert. $current = $this->parent->{$this->otherKey}; - + // Check if the current array exists or not on the parent model and create it // if it does not exist if (is_null($current)) $current = array(); $records = $this->formatSyncList($ids); - + $detach = array_diff($current, array_keys($records)); // Next, we will take the differences of the currents and given IDs and detach @@ -164,29 +81,6 @@ public function sync(array $ids, $detaching = true) $this->touchIfTouching(); } - /** - * Format the sync list so that it is keyed by ID. - * - * @param array $records - * @return array - */ - protected function formatSyncList(array $records) - { - $results = array(); - - foreach ($records as $id => $attributes) - { - if ( ! is_array($attributes)) - { - list($id, $attributes) = array($attributes, array()); - } - - $results[$id] = $attributes; - } - - return $results; - } - /** * Attach all of the IDs that aren't in the current array. * @@ -220,25 +114,25 @@ protected function attachNew(array $records, array $current, $touch = true) public function attach($id, array $attributes = array(), $touch = true) { if ($id instanceof Model) $id = $id->getKey(); - + // Generate a new parent query instance $parent = $this->newParentQuery(); - + // Generate a new related query instance $related = $this->related->newInstance(); - + // Set contraints on the related query $related = $related->where($this->related->getKeyName(), $id); $records = $this->createAttachRecords((array) $id, $attributes); - + // Get the ID's to attach to the two documents $otherIds = array_pluck($records, $this->otherKey); $foreignIds = array_pluck($records, $this->foreignKey); // Attach to the parent model $parent->push($this->otherKey, $otherIds[0])->update(array()); - + // Attach to the related model $related->push($this->foreignKey, $foreignIds[0])->update(array()); } @@ -296,54 +190,22 @@ public function detach($ids = array(), $touch = true) { $query->pull($this->otherKey, $id); } - - return count($ids); - } - - /** - * If we're touching the parent model, touch. - * - * @return void - */ - public function touchIfTouching() - { - if ($this->touchingParent()) $this->getParent()->touch(); - if ($this->getParent()->touches($this->relationName)) $this->touch(); - } - - /** - * Determine if we should touch the parent on sync. - * - * @return bool - */ - protected function touchingParent() - { - return $this->getRelated()->touches($this->guessInverseRelation()); - } - - /** - * Attempt to guess the name of the inverse of the relation. - * - * @return string - */ - protected function guessInverseRelation() - { - return strtolower(str_plural(class_basename($this->getParent()))); + return count($ids); } /** * Create a new query builder for the parent - * + * * @return Jenssegers\Mongodb\Builder */ protected function newParentQuery() { $query = $this->parent->newQuery(); - + return $query->where($this->parent->getKeyName(), '=', $this->parent->getKey()); } - + /** * Build model dictionary keyed by the relation's foreign key. * @@ -370,16 +232,6 @@ protected function buildDictionary(Collection $results) return $dictionary; } - /** - * Get the related model's updated at column name. - * - * @return string - */ - public function getRelatedFreshUpdate() - { - return array($this->related->getUpdatedAtColumn() => $this->related->freshTimestamp()); - } - /** * Get the fully qualified foreign key for the relation. * @@ -399,4 +251,4 @@ public function getOtherKey() { return $this->otherKey; } -} \ No newline at end of file +} diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 2b9c0bef0..6492ecf33 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -2,214 +2,214 @@ class RelationsTest extends PHPUnit_Framework_TestCase { - public function setUp() { + public function setUp() { } public function tearDown() { - User::truncate(); - Book::truncate(); - Item::truncate(); - Role::truncate(); - Client::truncate(); + User::truncate(); + Book::truncate(); + Item::truncate(); + Role::truncate(); + Client::truncate(); } public function testHasMany() { - $author = User::create(array('name' => 'George R. R. Martin')); - Book::create(array('title' => 'A Game of Thrones', 'author_id' => $author->_id)); - Book::create(array('title' => 'A Clash of Kings', 'author_id' => $author->_id)); + $author = User::create(array('name' => 'George R. R. Martin')); + Book::create(array('title' => 'A Game of Thrones', 'author_id' => $author->_id)); + Book::create(array('title' => 'A Clash of Kings', 'author_id' => $author->_id)); - $books = $author->books; - $this->assertEquals(2, count($books)); + $books = $author->books; + $this->assertEquals(2, count($books)); - $user = User::create(array('name' => 'John Doe')); - Item::create(array('type' => 'knife', 'user_id' => $user->_id)); - Item::create(array('type' => 'shield', 'user_id' => $user->_id)); - Item::create(array('type' => 'sword', 'user_id' => $user->_id)); - Item::create(array('type' => 'bag', 'user_id' => null)); + $user = User::create(array('name' => 'John Doe')); + Item::create(array('type' => 'knife', 'user_id' => $user->_id)); + Item::create(array('type' => 'shield', 'user_id' => $user->_id)); + Item::create(array('type' => 'sword', 'user_id' => $user->_id)); + Item::create(array('type' => 'bag', 'user_id' => null)); - $items = $user->items; - $this->assertEquals(3, count($items)); - } + $items = $user->items; + $this->assertEquals(3, count($items)); +} public function testBelongsTo() { - $user = User::create(array('name' => 'George R. R. Martin')); - Book::create(array('title' => 'A Game of Thrones', 'author_id' => $user->_id)); - $book = Book::create(array('title' => 'A Clash of Kings', 'author_id' => $user->_id)); + $user = User::create(array('name' => 'George R. R. Martin')); + Book::create(array('title' => 'A Game of Thrones', 'author_id' => $user->_id)); + $book = Book::create(array('title' => 'A Clash of Kings', 'author_id' => $user->_id)); - $author = $book->author; - $this->assertEquals('George R. R. Martin', $author->name); + $author = $book->author; + $this->assertEquals('George R. R. Martin', $author->name); - $user = User::create(array('name' => 'John Doe')); - $item = Item::create(array('type' => 'sword', 'user_id' => $user->_id)); + $user = User::create(array('name' => 'John Doe')); + $item = Item::create(array('type' => 'sword', 'user_id' => $user->_id)); - $owner = $item->user; - $this->assertEquals('John Doe', $owner->name); + $owner = $item->user; + $this->assertEquals('John Doe', $owner->name); } public function testHasOne() { - $user = User::create(array('name' => 'John Doe')); - Role::create(array('type' => 'admin', 'user_id' => $user->_id)); + $user = User::create(array('name' => 'John Doe')); + Role::create(array('type' => 'admin', 'user_id' => $user->_id)); - $role = $user->role; - $this->assertEquals('admin', $role->type); + $role = $user->role; + $this->assertEquals('admin', $role->type); } public function testWithBelongsTo() { - $user = User::create(array('name' => 'John Doe')); - Item::create(array('type' => 'knife', 'user_id' => $user->_id)); - Item::create(array('type' => 'shield', 'user_id' => $user->_id)); - Item::create(array('type' => 'sword', 'user_id' => $user->_id)); - Item::create(array('type' => 'bag', 'user_id' => null)); - - $items = Item::with('user')->get(); - - $user = $items[0]->getRelation('user'); - $this->assertInstanceOf('User', $user); - $this->assertEquals('John Doe', $user->name); - $this->assertEquals(1, count($items[0]->getRelations())); - $this->assertEquals(null, $items[3]->getRelation('user')); + $user = User::create(array('name' => 'John Doe')); + Item::create(array('type' => 'knife', 'user_id' => $user->_id)); + Item::create(array('type' => 'shield', 'user_id' => $user->_id)); + Item::create(array('type' => 'sword', 'user_id' => $user->_id)); + Item::create(array('type' => 'bag', 'user_id' => null)); + + $items = Item::with('user')->get(); + + $user = $items[0]->getRelation('user'); + $this->assertInstanceOf('User', $user); + $this->assertEquals('John Doe', $user->name); + $this->assertEquals(1, count($items[0]->getRelations())); + $this->assertEquals(null, $items[3]->getRelation('user')); } public function testWithHashMany() { - $user = User::create(array('name' => 'John Doe')); - Item::create(array('type' => 'knife', 'user_id' => $user->_id)); - Item::create(array('type' => 'shield', 'user_id' => $user->_id)); - Item::create(array('type' => 'sword', 'user_id' => $user->_id)); - Item::create(array('type' => 'bag', 'user_id' => null)); + $user = User::create(array('name' => 'John Doe')); + Item::create(array('type' => 'knife', 'user_id' => $user->_id)); + Item::create(array('type' => 'shield', 'user_id' => $user->_id)); + Item::create(array('type' => 'sword', 'user_id' => $user->_id)); + Item::create(array('type' => 'bag', 'user_id' => null)); - $user = User::with('items')->find($user->_id); + $user = User::with('items')->find($user->_id); - $items = $user->getRelation('items'); - $this->assertEquals(3, count($items)); - $this->assertInstanceOf('Item', $items[0]); + $items = $user->getRelation('items'); + $this->assertEquals(3, count($items)); + $this->assertInstanceOf('Item', $items[0]); } public function testWithHasOne() { - $user = User::create(array('name' => 'John Doe')); - Role::create(array('type' => 'admin', 'user_id' => $user->_id)); - Role::create(array('type' => 'guest', 'user_id' => $user->_id)); + $user = User::create(array('name' => 'John Doe')); + Role::create(array('type' => 'admin', 'user_id' => $user->_id)); + Role::create(array('type' => 'guest', 'user_id' => $user->_id)); - $user = User::with('role')->find($user->_id); + $user = User::with('role')->find($user->_id); - $role = $user->getRelation('role'); - $this->assertInstanceOf('Role', $role); - $this->assertEquals('admin', $role->type); + $role = $user->getRelation('role'); + $this->assertInstanceOf('Role', $role); + $this->assertEquals('admin', $role->type); } public function testEasyRelation() { - // Has Many - $user = User::create(array('name' => 'John Doe')); - $item = Item::create(array('type' => 'knife')); - $user->items()->save($item); - - $user = User::find($user->_id); - $items = $user->items; - $this->assertEquals(1, count($items)); - $this->assertInstanceOf('Item', $items[0]); - - // Has one - $user = User::create(array('name' => 'John Doe')); - $role = Role::create(array('type' => 'admin')); - $user->role()->save($role); - - $user = User::find($user->_id); - $role = $user->role; - $this->assertInstanceOf('Role', $role); - $this->assertEquals('admin', $role->type); + // Has Many + $user = User::create(array('name' => 'John Doe')); + $item = Item::create(array('type' => 'knife')); + $user->items()->save($item); + + $user = User::find($user->_id); + $items = $user->items; + $this->assertEquals(1, count($items)); + $this->assertInstanceOf('Item', $items[0]); + + // Has one + $user = User::create(array('name' => 'John Doe')); + $role = Role::create(array('type' => 'admin')); + $user->role()->save($role); + + $user = User::find($user->_id); + $role = $user->role; + $this->assertInstanceOf('Role', $role); + $this->assertEquals('admin', $role->type); + } + + public function testHasManyAndBelongsTo() + { + $user = User::create(array('name' => 'John Doe')); + + $user->clients()->save(new Client(array('name' => 'Pork Pies Ltd.'))); + $user->clients()->create(array('name' => 'Buffet Bar Inc.')); + + $user = User::with('clients')->find($user->_id); + + $client = Client::with('users')->first(); + + $clients = $client->getRelation('users'); + $users = $user->getRelation('clients'); + + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $clients); + $this->assertInstanceOf('Client', $users[0]); + $this->assertInstanceOf('User', $clients[0]); + $this->assertCount(2, $user->clients); + $this->assertCount(1, $client->users); + + // Now create a new user to an existing client + $client->users()->create(array('name' => 'Jane Doe')); + + $otherClient = User::where('name', '=', 'Jane Doe')->first()->clients()->get(); + + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $otherClient); + $this->assertInstanceOf('Client', $otherClient[0]); + $this->assertCount(1, $otherClient); + + // Now attach an existing client to an existing user + $user = User::where('name', '=', 'Jane Doe')->first(); + $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); + + // Check the models are what they should be + $this->assertInstanceOf('Client', $client); + $this->assertInstanceOf('User', $user); + + // Assert they are not attached + $this->assertFalse(in_array($client->_id, $user->client_ids)); + $this->assertFalse(in_array($user->_id, $client->user_ids)); + + // Attach the client to the user + $user->clients()->attach($client); + + // Get the new user model + $user = User::where('name', '=', 'Jane Doe')->first(); + $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); + + // Assert they are attached + $this->assertTrue(in_array($client->_id, $user->client_ids)); + $this->assertTrue(in_array($user->_id, $client->user_ids)); + } + + public function testHasManyAndBelongsToAttachesExistingModels() + { + $user = User::create(array('name' => 'John Doe', 'client_ids' => array('1234523'))); + + $clients = array( + Client::create(array('name' => 'Pork Pies Ltd.'))->_id, + Client::create(array('name' => 'Buffet Bar Inc.'))->_id + ); + + $moreClients = array( + Client::create(array('name' => 'Boloni Ltd.'))->_id, + Client::create(array('name' => 'Meatballs Inc.'))->_id + ); + + // Sync multiple records + $user->clients()->sync($clients); + + $user = User::with('clients')->find($user->_id); + + // Assert non attached ID's are detached succesfully + $this->assertFalse(in_array('1234523', $user->client_ids)); + + // Assert there are two client objects in the relationship + $this->assertCount(2, $user->clients); + + $user->clients()->sync($moreClients); + + $user = User::with('clients')->find($user->_id); + + // Assert there are now 4 client objects in the relationship + $this->assertCount(4, $user->clients); } - - public function testHasManyAndBelongsTo() - { - $user = User::create(array('name' => 'John Doe')); - - $user->clients()->save(new Client(array('name' => 'Pork Pies Ltd.'))); - $user->clients()->create(array('name' => 'Buffet Bar Inc.')); - - $user = User::with('clients')->find($user->_id); - - $client = Client::with('users')->first(); - - $clients = $client->getRelation('users'); - $users = $user->getRelation('clients'); - - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $clients); - $this->assertInstanceOf('Client', $users[0]); - $this->assertInstanceOf('User', $clients[0]); - $this->assertCount(2, $user->clients); - $this->assertCount(1, $client->users); - - // Now create a new user to an existing client - $client->users()->create(array('name' => 'Jane Doe')); - - $otherClient = User::where('name', '=', 'Jane Doe')->first()->clients()->get(); - - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $otherClient); - $this->assertInstanceOf('Client', $otherClient[0]); - $this->assertCount(1, $otherClient); - - // Now attach an existing client to an existing user - $user = User::where('name', '=', 'Jane Doe')->first(); - $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); - - // Check the models are what they should be - $this->assertInstanceOf('Client', $client); - $this->assertInstanceOf('User', $user); - - // Assert they are not attached - $this->assertFalse(in_array($client->_id, $user->client_ids)); - $this->assertFalse(in_array($user->_id, $client->user_ids)); - - // Attach the client to the user - $user->clients()->attach($client); - - // Get the new user model - $user = User::where('name', '=', 'Jane Doe')->first(); - $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); - - // Assert they are attached - $this->assertTrue(in_array($client->_id, $user->client_ids)); - $this->assertTrue(in_array($user->_id, $client->user_ids)); - } - - public function testHasManyAndBelongsToAttachesExistingModels() - { - $user = User::create(array('name' => 'John Doe', 'client_ids' => array('1234523'))); - - $clients = array( - Client::create(array('name' => 'Pork Pies Ltd.'))->_id, - Client::create(array('name' => 'Buffet Bar Inc.'))->_id - ); - - $moreClients = array( - Client::create(array('name' => 'Boloni Ltd.'))->_id, - Client::create(array('name' => 'Meatballs Inc.'))->_id - ); - - // Sync multiple records - $user->clients()->sync($clients); - - $user = User::with('clients')->find($user->_id); - - // Assert non attached ID's are detached succesfully - $this->assertFalse(in_array('1234523', $user->client_ids)); - - // Assert there are two client objects in the relationship - $this->assertCount(2, $user->clients); - - $user->clients()->sync($moreClients); - - $user = User::with('clients')->find($user->_id); - - // Assert there are now 4 client objects in the relationship - $this->assertCount(4, $user->clients); - } } From 485c25af35d27d19a78e193945165c01f0e4c42e Mon Sep 17 00:00:00 2001 From: Jens Segers Date: Wed, 20 Nov 2013 22:43:43 +0100 Subject: [PATCH 3/9] Tweaking BelongsToMany namespaces --- src/Jenssegers/Mongodb/Relations/BelongsToMany.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php index d09967c05..58ba8e58f 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php @@ -1,8 +1,7 @@ Date: Thu, 21 Nov 2013 10:42:01 +0100 Subject: [PATCH 4/9] Small readme update for belongsToMany --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 005f9ba73..5766bfa4a 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,8 @@ Supported relations are: - belongsTo - belongsToMany +*The belongsToMany relation will not use a pivot "table", but will push id's to a **related_ids** attribute instead.* + Example: use Jenssegers\Mongodb\Model as Eloquent; From 293fa5c37e14bdc4244591da2529adab3be4d2e0 Mon Sep 17 00:00:00 2001 From: Jens Segers Date: Thu, 21 Nov 2013 10:43:32 +0100 Subject: [PATCH 5/9] Markdown fixes --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 5766bfa4a..ce88b8144 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,6 @@ If you are using a different database driver as the default one, you will need t Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent ### Optional: Alias -------------------- You may also register an alias for the MongoDB model by adding the following to the alias array in `app/config/app.php`: @@ -268,7 +267,7 @@ Supported relations are: - belongsTo - belongsToMany -*The belongsToMany relation will not use a pivot "table", but will push id's to a **related_ids** attribute instead.* +*The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead.* Example: From e9b83e56c07b91c2050934903fba1e5fece1c0c5 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 21 Nov 2013 10:33:35 +0000 Subject: [PATCH 6/9] conflicts --- .settings/org.eclipse.core.resources.prefs | 2 + README.md | 5 +- README.md.conflict | 370 +++++++++++++++++++++ 3 files changed, 374 insertions(+), 3 deletions(-) create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 README.md.conflict diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..8a34f2ce5 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/README.md=UTF-8 diff --git a/README.md b/README.md index ce88b8144..ef7cbcc2d 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ If you are using a different database driver as the default one, you will need t Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent ### Optional: Alias +------------------- You may also register an alias for the MongoDB model by adding the following to the alias array in `app/config/app.php`: @@ -267,8 +268,6 @@ Supported relations are: - belongsTo - belongsToMany -*The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead.* - Example: use Jenssegers\Mongodb\Model as Eloquent; @@ -367,4 +366,4 @@ By default, Laravel keeps a log in memory of all queries that have been run for DB::connection()->disableQueryLog(); -*From: http://laravel.com/docs/database#query-logging* +*From: http://laravel.com/docs/database#query-logging* \ No newline at end of file diff --git a/README.md.conflict b/README.md.conflict new file mode 100644 index 000000000..ce88b8144 --- /dev/null +++ b/README.md.conflict @@ -0,0 +1,370 @@ +Laravel MongoDB +=============== + +[![Latest Stable Version](https://poser.pugx.org/jenssegers/mongodb/v/stable.png)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](https://poser.pugx.org/jenssegers/mongodb/downloads.png)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](https://travis-ci.org/jenssegers/Laravel-MongoDB.png?branch=master)](https://travis-ci.org/jenssegers/Laravel-MongoDB) + +An Eloquent model and Query builder with support for MongoDB, inspired by LMongo, but using the original Laravel methods. *This library extends the original Laravel classes, so it uses exactly the same methods.* + +Installation +------------ + +Add the package to your `composer.json` and run `composer update`. + + { + "require": { + "jenssegers/mongodb": "*" + } + } + +Add the service provider in `app/config/app.php`: + + 'Jenssegers\Mongodb\MongodbServiceProvider', + +The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects. + +Configuration +------------- + +Change your default database connection name in `app/config/database.php`: + + 'default' => 'mongodb', + +And add a new mongodb connection: + + 'mongodb' => array( + 'driver' => 'mongodb', + 'host' => 'localhost', + 'port' => 27017, + 'username' => 'username', + 'password' => 'password', + 'database' => 'database' + ), + +You can connect to multiple servers or replica sets with the following configuration: + + 'mongodb' => array( + 'driver' => 'mongodb', + 'host' => array('server1', 'server2), + 'port' => 27017, + 'username' => 'username', + 'password' => 'password', + 'database' => 'database', + 'options' => array('replicaSet' => 'replicaSetName') + ), + +Eloquent +-------- + +Tell your model to use the MongoDB model and set the collection (alias for table) property. The lower-case, plural name of the class will be used for the collection name, unless another name is explicitly specified. + + use Jenssegers\Mongodb\Model as Eloquent; + + class MyModel extends Eloquent { + + protected $collection = 'mycollection'; + + } + +If you are using a different database driver as the default one, you will need to specify the mongodb connection within your model by changing the `connection` property: + + use Jenssegers\Mongodb\Model as Eloquent; + + class MyModel extends Eloquent { + + protected $connection = 'mongodb'; + + } + +Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent + +### Optional: Alias + +You may also register an alias for the MongoDB model by adding the following to the alias array in `app/config/app.php`: + + 'Moloquent' => 'Jenssegers\Mongodb\Model', + +This will allow you to use your registered alias like: + + class MyModel extends Moloquent { + + protected $collection = 'mycollection'; + + } + +Query Builder +------------- + +The database driver plugs right into the original query builder. When using mongodb connections you will be able to build fluent queries to perform database operations. For your convenience, there is a `collection` alias for `table` as well as some additional mongodb specific operations like `push` and `pull`. + + // With custom connection + $user = DB::connection('mongodb')->collection('users')->get(); + + // Using default connection + $users = DB::collection('users')->get(); + $user = DB::collection('users')->where('name', 'John')->first(); + +Read more about the query builder on http://laravel.com/docs/queries + +Schema +------ + +The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: + + Schema::create('users', function($collection) + { + $collection->index('name'); + $collection->unique('email'); + }); + +Supported operations are: + + - create and drop + - collection + - hasCollection + - index and dropIndex (compound indexes supported as well) + - unique + - background, sparse, expire (MongoDB specific) + +Read more about the schema builder on http://laravel.com/docs/schema + +Sessions +-------- + +The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session + +Examples +-------- + +### Basic Usage + +**Retrieving All Models** + + $users = User::all(); + +**Retrieving A Record By Primary Key** + + $user = User::find('517c43667db388101e00000f'); + +**Wheres** + + $users = User::where('votes', '>', 100)->take(10)->get(); + +**Or Statements** + + $users = User::where('votes', '>', 100)->orWhere('name', 'John')->get(); + +**Using Where In With An Array** + + $users = User::whereIn('age', array(16, 18, 20))->get(); + +When using `whereNotIn` objects will be returned if the field is non existent. Combine with `whereNotNull('age')` to leave out those documents. + +**Using Where Between** + + $users = User::whereBetween('votes', array(1, 100))->get(); + +**Where null** + + $users = User::whereNull('updated_at')->get(); + +**Order By** + + $users = User::orderBy('name', 'desc')->get(); + +**Offset & Limit** + + $users = User::skip(10)->take(5)->get(); + +**Distinct** + +Distinct requires a field for which to return the distinct values. + + $users = User::distinct()->get(array('name')); + // or + $users = User::distinct('name')->get(); + +Distinct can be combined with **where**: + + $users = User::where('active', true)->distinct('name')->get(); + +**Advanced Wheres** + + $users = User::where('name', '=', 'John')->orWhere(function($query) + { + $query->where('votes', '>', 100) + ->where('title', '<>', 'Admin'); + }) + ->get(); + +**Group By** + +Selected columns that are not grouped will be aggregated with the $last function. + + $users = Users::groupBy('title')->get(array('title', 'name')); + +**Aggregation** + +*Aggregations are only available for MongoDB versions greater than 2.2.* + + $total = Order::count(); + $price = Order::max('price'); + $price = Order::min('price'); + $price = Order::avg('price'); + $total = Order::sum('price'); + +Aggregations can be combined with **where**: + + $sold = Orders::where('sold', true)->sum('price'); + +**Like** + + $user = Comment::where('body', 'like', '%spam%')->get(); + +**Incrementing or decrementing a value of a column** + +Perform increments or decrements (default 1) on specified attributes: + + User::where('name', 'John Doe')->increment('age'); + User::where('name', 'Jaques')->decrement('weight', 50); + +The number of updated objects is returned: + + $count = User->increment('age'); + +You may also specify additional columns to update: + + User::where('age', '29')->increment('age', 1, array('group' => 'thirty something')); + User::where('bmi', 30)->decrement('bmi', 1, array('category' => 'overweight')); + +### Inserts, updates and deletes + +All basic insert, update, delete and select methods should be implemented. + +### Dates + +Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators + +Example: + + use Jenssegers\Mongodb\Model as Eloquent; + + class User extends Eloquent { + + protected $dates = array('birthday'); + + } + +Which allows you to execute queries like: + + $users = User::where('birthday', '>', new DateTime('-18 years'))->get(); + +### Relations + +Supported relations are: + + - hasOne + - hasMany + - belongsTo + - belongsToMany + +*The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead.* + +Example: + + use Jenssegers\Mongodb\Model as Eloquent; + + class User extends Eloquent { + + public function items() + { + return $this->hasMany('Item'); + } + + } + +And the inverse relation: + + use Jenssegers\Mongodb\Model as Eloquent; + + class Item extends Eloquent { + + public function user() + { + return $this->belongsTo('User'); + } + + } + +Other relations are not yet supported, but may be added in the future. Read more about these relations on http://four.laravel.com/docs/eloquent#relationships + +### Raw Expressions + +These expressions will be injected directly into the query. + + User::whereRaw(array('age' => array('$gt' => 30, '$lt' => 40)))->get(); + +You can also perform raw expressions on the internal MongoCollection object, note that this will return the original response, and not a collection of models. + + User::raw(function($collection) + { + return $collection->find(); + }); + +Or you can access the internal MongoCollection object directly: + + User::raw()->find(); + +The MongoClient and MongoDB objects can be accessed like this: + + $client = DB::getMongoClient(); + $db = DB::getMongoDB(); + +### MongoDB specific operations + +**Upsert** + +Update or insert a document. Additional options for the update method are passed directly to the native update method. + + DB::collection('users')->where('name', 'John') + ->update($data, array('upsert' => true)); + +**Push** + +Add an items to an array. + + DB::collection('users')->where('name', 'John')->push('items', 'boots'); + DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); + +**Pull** + +Remove an item from an array. + + DB::collection('users')->where('name', 'John')->pull('items', 'boots'); + DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); + +**Unset** + +Remove one or more fields from a document. + + DB::collection('users')->where('name', 'John')->unset('note'); + +You can also perform an unset on a model. + + $user = User::where('name', 'John')->first(); + $user->unset('note'); + +### Query Caching + +You may easily cache the results of a query using the remember method: + + $users = User::remember(10)->get(); + +*From: http://laravel.com/docs/queries#caching-queries* + +### Query Logging + +By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the `disableQueryLog` method: + + DB::connection()->disableQueryLog(); + +*From: http://laravel.com/docs/database#query-logging* From cc77faea2b8d7aa36c78b5797fb5bc8b1f370b17 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 21 Nov 2013 10:36:35 +0000 Subject: [PATCH 7/9] removed conflict --- README.md.conflict | 370 --------------------------------------------- 1 file changed, 370 deletions(-) delete mode 100644 README.md.conflict diff --git a/README.md.conflict b/README.md.conflict deleted file mode 100644 index ce88b8144..000000000 --- a/README.md.conflict +++ /dev/null @@ -1,370 +0,0 @@ -Laravel MongoDB -=============== - -[![Latest Stable Version](https://poser.pugx.org/jenssegers/mongodb/v/stable.png)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](https://poser.pugx.org/jenssegers/mongodb/downloads.png)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](https://travis-ci.org/jenssegers/Laravel-MongoDB.png?branch=master)](https://travis-ci.org/jenssegers/Laravel-MongoDB) - -An Eloquent model and Query builder with support for MongoDB, inspired by LMongo, but using the original Laravel methods. *This library extends the original Laravel classes, so it uses exactly the same methods.* - -Installation ------------- - -Add the package to your `composer.json` and run `composer update`. - - { - "require": { - "jenssegers/mongodb": "*" - } - } - -Add the service provider in `app/config/app.php`: - - 'Jenssegers\Mongodb\MongodbServiceProvider', - -The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects. - -Configuration -------------- - -Change your default database connection name in `app/config/database.php`: - - 'default' => 'mongodb', - -And add a new mongodb connection: - - 'mongodb' => array( - 'driver' => 'mongodb', - 'host' => 'localhost', - 'port' => 27017, - 'username' => 'username', - 'password' => 'password', - 'database' => 'database' - ), - -You can connect to multiple servers or replica sets with the following configuration: - - 'mongodb' => array( - 'driver' => 'mongodb', - 'host' => array('server1', 'server2), - 'port' => 27017, - 'username' => 'username', - 'password' => 'password', - 'database' => 'database', - 'options' => array('replicaSet' => 'replicaSetName') - ), - -Eloquent --------- - -Tell your model to use the MongoDB model and set the collection (alias for table) property. The lower-case, plural name of the class will be used for the collection name, unless another name is explicitly specified. - - use Jenssegers\Mongodb\Model as Eloquent; - - class MyModel extends Eloquent { - - protected $collection = 'mycollection'; - - } - -If you are using a different database driver as the default one, you will need to specify the mongodb connection within your model by changing the `connection` property: - - use Jenssegers\Mongodb\Model as Eloquent; - - class MyModel extends Eloquent { - - protected $connection = 'mongodb'; - - } - -Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent - -### Optional: Alias - -You may also register an alias for the MongoDB model by adding the following to the alias array in `app/config/app.php`: - - 'Moloquent' => 'Jenssegers\Mongodb\Model', - -This will allow you to use your registered alias like: - - class MyModel extends Moloquent { - - protected $collection = 'mycollection'; - - } - -Query Builder -------------- - -The database driver plugs right into the original query builder. When using mongodb connections you will be able to build fluent queries to perform database operations. For your convenience, there is a `collection` alias for `table` as well as some additional mongodb specific operations like `push` and `pull`. - - // With custom connection - $user = DB::connection('mongodb')->collection('users')->get(); - - // Using default connection - $users = DB::collection('users')->get(); - $user = DB::collection('users')->where('name', 'John')->first(); - -Read more about the query builder on http://laravel.com/docs/queries - -Schema ------- - -The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: - - Schema::create('users', function($collection) - { - $collection->index('name'); - $collection->unique('email'); - }); - -Supported operations are: - - - create and drop - - collection - - hasCollection - - index and dropIndex (compound indexes supported as well) - - unique - - background, sparse, expire (MongoDB specific) - -Read more about the schema builder on http://laravel.com/docs/schema - -Sessions --------- - -The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session - -Examples --------- - -### Basic Usage - -**Retrieving All Models** - - $users = User::all(); - -**Retrieving A Record By Primary Key** - - $user = User::find('517c43667db388101e00000f'); - -**Wheres** - - $users = User::where('votes', '>', 100)->take(10)->get(); - -**Or Statements** - - $users = User::where('votes', '>', 100)->orWhere('name', 'John')->get(); - -**Using Where In With An Array** - - $users = User::whereIn('age', array(16, 18, 20))->get(); - -When using `whereNotIn` objects will be returned if the field is non existent. Combine with `whereNotNull('age')` to leave out those documents. - -**Using Where Between** - - $users = User::whereBetween('votes', array(1, 100))->get(); - -**Where null** - - $users = User::whereNull('updated_at')->get(); - -**Order By** - - $users = User::orderBy('name', 'desc')->get(); - -**Offset & Limit** - - $users = User::skip(10)->take(5)->get(); - -**Distinct** - -Distinct requires a field for which to return the distinct values. - - $users = User::distinct()->get(array('name')); - // or - $users = User::distinct('name')->get(); - -Distinct can be combined with **where**: - - $users = User::where('active', true)->distinct('name')->get(); - -**Advanced Wheres** - - $users = User::where('name', '=', 'John')->orWhere(function($query) - { - $query->where('votes', '>', 100) - ->where('title', '<>', 'Admin'); - }) - ->get(); - -**Group By** - -Selected columns that are not grouped will be aggregated with the $last function. - - $users = Users::groupBy('title')->get(array('title', 'name')); - -**Aggregation** - -*Aggregations are only available for MongoDB versions greater than 2.2.* - - $total = Order::count(); - $price = Order::max('price'); - $price = Order::min('price'); - $price = Order::avg('price'); - $total = Order::sum('price'); - -Aggregations can be combined with **where**: - - $sold = Orders::where('sold', true)->sum('price'); - -**Like** - - $user = Comment::where('body', 'like', '%spam%')->get(); - -**Incrementing or decrementing a value of a column** - -Perform increments or decrements (default 1) on specified attributes: - - User::where('name', 'John Doe')->increment('age'); - User::where('name', 'Jaques')->decrement('weight', 50); - -The number of updated objects is returned: - - $count = User->increment('age'); - -You may also specify additional columns to update: - - User::where('age', '29')->increment('age', 1, array('group' => 'thirty something')); - User::where('bmi', 30)->decrement('bmi', 1, array('category' => 'overweight')); - -### Inserts, updates and deletes - -All basic insert, update, delete and select methods should be implemented. - -### Dates - -Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators - -Example: - - use Jenssegers\Mongodb\Model as Eloquent; - - class User extends Eloquent { - - protected $dates = array('birthday'); - - } - -Which allows you to execute queries like: - - $users = User::where('birthday', '>', new DateTime('-18 years'))->get(); - -### Relations - -Supported relations are: - - - hasOne - - hasMany - - belongsTo - - belongsToMany - -*The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead.* - -Example: - - use Jenssegers\Mongodb\Model as Eloquent; - - class User extends Eloquent { - - public function items() - { - return $this->hasMany('Item'); - } - - } - -And the inverse relation: - - use Jenssegers\Mongodb\Model as Eloquent; - - class Item extends Eloquent { - - public function user() - { - return $this->belongsTo('User'); - } - - } - -Other relations are not yet supported, but may be added in the future. Read more about these relations on http://four.laravel.com/docs/eloquent#relationships - -### Raw Expressions - -These expressions will be injected directly into the query. - - User::whereRaw(array('age' => array('$gt' => 30, '$lt' => 40)))->get(); - -You can also perform raw expressions on the internal MongoCollection object, note that this will return the original response, and not a collection of models. - - User::raw(function($collection) - { - return $collection->find(); - }); - -Or you can access the internal MongoCollection object directly: - - User::raw()->find(); - -The MongoClient and MongoDB objects can be accessed like this: - - $client = DB::getMongoClient(); - $db = DB::getMongoDB(); - -### MongoDB specific operations - -**Upsert** - -Update or insert a document. Additional options for the update method are passed directly to the native update method. - - DB::collection('users')->where('name', 'John') - ->update($data, array('upsert' => true)); - -**Push** - -Add an items to an array. - - DB::collection('users')->where('name', 'John')->push('items', 'boots'); - DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); - -**Pull** - -Remove an item from an array. - - DB::collection('users')->where('name', 'John')->pull('items', 'boots'); - DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); - -**Unset** - -Remove one or more fields from a document. - - DB::collection('users')->where('name', 'John')->unset('note'); - -You can also perform an unset on a model. - - $user = User::where('name', 'John')->first(); - $user->unset('note'); - -### Query Caching - -You may easily cache the results of a query using the remember method: - - $users = User::remember(10)->get(); - -*From: http://laravel.com/docs/queries#caching-queries* - -### Query Logging - -By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the `disableQueryLog` method: - - DB::connection()->disableQueryLog(); - -*From: http://laravel.com/docs/database#query-logging* From de0d88906b053ca4f368f72eaa32de0d51329f53 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 21 Nov 2013 11:16:19 +0000 Subject: [PATCH 8/9] removed settings --- .settings/org.eclipse.core.resources.prefs | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 .settings/org.eclipse.core.resources.prefs diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 8a34f2ce5..000000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/README.md=UTF-8 From fd5a4702633a696f4766f3fb14ab029b35741140 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 21 Nov 2013 11:20:08 +0000 Subject: [PATCH 9/9] updated gitgnore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index a4a4579c3..afe97b1e0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .DS_Store phpunit.phar /vendor +/.settings composer.phar composer.lock *.sublime-project