@@ -10,9 +10,9 @@ An Eloquent model and Query builder with support for MongoDB, using the original
In this new version, embedded documents are no longer saved to the parent model using an attribute with a leading underscore. If you have a relation like `embedsMany('Book')`, these books are now stored under `$model['books']` instead of `$model['_books']`. This was changed to make embedded relations less confusing for new developers.
If you want to upgrade to this new version without having to change all your existing database objects, you can modify your embedded relations to use a non-default local key including the underscore:
$this->embedsMany('Book', '_books');
```php
$this->embedsMany('Book','_books');
```
Read the full changelog at https://github.com/jenssegers/laravel-mongodb/releases/tag/v2.0.0
Installation
...
...
@@ -21,113 +21,113 @@ Installation
Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongo.installation.php
Install using composer:
composer require jenssegers/mongodb
```json
composerrequirejenssegers/mongodb
```
Add the service provider in `app/config/app.php`:
'Jenssegers\Mongodb\MongodbServiceProvider',
```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',
```php
'default'=>'mongodb',
```
And add a new mongodb connection:
'mongodb' => array(
'driver' => 'mongodb',
'host' => 'localhost',
'port' => 27017,
'username' => 'username',
'password' => 'password',
'database' => 'database'
),
```php
'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:
This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class User extends Eloquent {}
classUserextendsEloquent{}
```
Note that we did not tell Eloquent which collection to use for the `User` model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a `collection` property on your model:
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class User extends Eloquent {
classUserextendsEloquent{
protected $collection = 'users_collection';
}
protected$collection='users_collection';
}
```
**NOTE:** Eloquent will also assume that each collection has a primary key column named id. You may define a `primaryKey` property to override this convention. Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model.
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class MyModel extends Eloquent {
classMyModelextendsEloquent{
protected $connection = 'mongodb';
}
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',
```php
'Moloquent'=>'Jenssegers\Mongodb\Model',
```
This will allow you to use the registered alias like:
class MyModel extends Moloquent {}
```php
classMyModelextendsMoloquent{}
```
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 operators/operations.
This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. If you don't use password reminders, you don't have to register this service provider and everything else should work just fine.
### Sentry
...
...
@@ -166,144 +166,144 @@ Troubleshooting
The `MongoClient` class is part of the MongoDB PHP driver. Usually, this error means that you forgot to install, or did not install this driver correctly. You can find installation instructions for this driver at http://php.net/manual/en/mongo.installation.php.
To check if you have installed the driver correctly, run the following command:
$ php -i | grep 'Mongo'
MongoDB Support => enabled
```sh
$ php -i | grep'Mongo'
MongoDB Support => enabled
```
#### Argument 2 passed to Illuminate\Database\Query\Builder::__construct() must be an instance of Illuminate\Database\Query\Grammars\Grammar, null given
To solve this, you will need to check two things. First check if your model is extending the correct class; this class should be `Jenssegers\Mongodb\Model`. Secondly, check if your model is using a MongoDB connection. If you did not change the default database connection in your database configuration file, you need to specify the MongoDB enabled connection. This is what your class should look like if you did not set up an alias and change the default database connection:
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:
```php
useJenssegers\Mongodb\Eloquent\SoftDeletingTrait;
use Jenssegers\Mongodb\Eloquent\SoftDeletingTrait;
class User extends Eloquent {
classUserextendsEloquent{
use SoftDeletingTrait;
useSoftDeletingTrait;
protected $dates = ['deleted_at'];
}
protected$dates=['deleted_at'];
}
```
For more information check http://laravel.com/docs/eloquent#soft-deleting
### MongoDB specific operators
...
...
@@ -311,47 +311,47 @@ For more information check http://laravel.com/docs/eloquent#soft-deleting
**Exists**
Matches documents that have the specified field.
User::where('age', 'exists', true)->get();
```php
User::where('age','exists',true)->get();
```
**All**
Matches arrays that contain all elements specified in the query.
**NOTE:** you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoRegex object.
Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
User::where('age', 'type', 2)->get();
```php
User::where('age','type',2)->get();
```
**Mod**
Performs a modulo operation on the value of a field and selects documents with a specified result.
User::where('age', 'mod', array(10, 0))->get();
```php
User::where('age','mod',array(10,0))->get();
```
**Where**
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where
...
...
@@ -361,36 +361,36 @@ Matches documents that satisfy a JavaScript expression. For more information che
Inserting, updating and deleting records works just like the original Eloquent.
**Saving a new model**
$user = new User;
$user->name = 'John';
$user->save();
```php
$user=newUser;
$user->name='John';
$user->save();
```
You may also use the create method to save a new model in a single line:
User::create(array('name' => 'John'));
```php
User::create(array('name'=>'John'));
```
**Updating a model**
To update a model, you may retrieve it, change an attribute, and use the save method.
$user = User::first();
$user->email = 'john@foo.com';
$user->save();
```php
$user=User::first();
$user->email='john@foo.com';
$user->save();
```
*There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations*
**Deleting a model**
To delete a model, simply call the delete method on the instance:
$user = User::first();
$user->delete();
```php
$user=User::first();
$user->delete();
```
Or deleting a model by its key:
User::destroy('517c43667db388101e00000f');
```php
User::destroy('517c43667db388101e00000f');
```
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete
### Dates
...
...
@@ -398,19 +398,19 @@ For more information about model manipulation, check http://laravel.com/docs/elo
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:
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class User extends Eloquent {
protected $dates = array('birthday');
classUserextendsEloquent{
}
protected$dates=array('birthday');
}
```
Which allows you to execute queries like:
$users = User::where('birthday', '>', new DateTime('-18 years'))->get();
The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to `null`:
Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships
### EmbedsMany Relations
If you want to embed models, rather than referencing them, you can use the `embedsMany` relation. This relation is similar to the `hasMany` relation, but embeds the models inside the parent object.
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class User extends Eloquent {
public function books()
{
return $this->embedsMany('Book');
}
classUserextendsEloquent{
publicfunctionbooks()
{
return$this->embedsMany('Book');
}
}
```
You access the embedded models through the dynamic property:
$books = User::first()->books;
```php
$books=User::first()->books;
```
The inverse relation is auto*magically* available, you don't need to define this reverse relation.
$user = $book->user;
```php
$user=$book->user;
```
Inserting and updating embedded models works similar to the `hasMany` relation:
```php
$book=newBook(array('title'=>'A Game of Thrones'));
$book = new Book(array('title' => 'A Game of Thrones'));
$user = User::first();
$book = $user->books()->save($book);
// or
$book = $user->books()->create(array('title' => 'A Game of Thrones'))
$user=User::first();
$book=$user->books()->save($book);
// or
$book=$user->books()->create(array('title'=>'A Game of Thrones'))
```
You can update embedded models using their `save` method (available since release 2.0.0):
```php
$book=$user->books()->first();
$book = $user->books()->first();
$book->title = 'A Game of Thrones';
$book->save();
$book->title='A Game of Thrones';
$book->save();
```
You can remove an embedded model by using the `destroy` method on the relation, or the `delete` method on the model (available since release 2.0.0):
```php
$book=$user->books()->first();
$book = $user->books()->first();
$book->delete();
// or
$user->books()->destroy($book);
$book->delete();
// or
$user->books()->destroy($book);
```
If you want to add or remove an embedded model, without touching the database, you can use the `associate` and `dissociate` methods. To eventually write the changes to the database, save the parent object:
```php
$user->books()->associate($book);
$user->books()->associate($book);
$user->save();
$user->save();
```
Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:
return $this->embedsMany('Book', 'local_key');
```php
return$this->embedsMany('Book','local_key');
```
Embedded relations will return a Collection of embedded items instead of a query builder. To allow a more query-like behavior, a modified version of the Collection class is used, with support for the following **additional** operations:
- where($key, $operator, $value)
...
...
@@ -533,177 +534,177 @@ Embedded relations will return a Collection of embedded items instead of a query
- skip($value)
This allows you to execute simple queries on the collection results:
**Note:** Because embedded models are not stored in a separate collection, you can not query all of embedded models. You will always have to access them through the parent model.
### EmbedsOne Relations
The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class Book extends Eloquent {
public function author()
{
return $this->embedsOne('Author');
}
classBookextendsEloquent{
publicfunctionauthor()
{
return$this->embedsOne('Author');
}
}
```
You access the embedded models through the dynamic property:
$author = Book::first()->author;
```php
$author=Book::first()->author;
```
Inserting and updating embedded models works similar to the `hasOne` relation:
```php
$author=newAuthor(array('name'=>'John Doe'));
$author = new Author(array('name' => 'John Doe'));
You can update the embedded model using the `save` method (available since release 2.0.0):
```php
$author=$book->author;
$author = $book->author;
$author->name = 'Jane Doe';
$author->save();
$author->name='Jane Doe';
$author->save();
```
You can replace the embedded model with a new model like this:
$newAuthor = new Author(array('name' => 'Jane Doe'));
$book->author()->save($newAuthor);
```php
$newAuthor=newAuthor(array('name'=>'Jane Doe'));
$book->author()->save($newAuthor);
```
### MySQL Relations
If you're using a hybrid MongoDB and SQL setup, you're in luck! The model will automatically return a MongoDB- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need to extend `Jenssegers\Eloquent\Model`. Note that this functionality only works for hasOne, hasMany and belongsTo relations.
Example SQL-based User model:
```php
useJenssegers\Eloquent\ModelasEloquent;
use Jenssegers\Eloquent\Model as Eloquent;
class User extends Eloquent {
protected $connection = 'mysql';
classUserextendsEloquent{
public function messages()
{
return $this->hasMany('Message');
}
protected$connection='mysql';
publicfunctionmessages()
{
return$this->hasMany('Message');
}
}
```
And the Mongodb-based Message model:
```php
useJenssegers\Mongodb\ModelasEloquent;
use Jenssegers\Mongodb\Model as Eloquent;
class Message extends Eloquent {
protected $connection = 'mongodb';
classMessageextendsEloquent{
public function user()
{
return $this->belongsTo('User');
}
protected$connection='mongodb';
publicfunctionuser()
{
return$this->belongsTo('User');
}
}
```
### Raw Expressions
These expressions will be injected directly into the query.
You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models. If this is executed on the query builder, it will return the original response.
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: