Commit f37336a1 authored by Jens Segers's avatar Jens Segers

Fix merge conflict

parents 4fc8f12f 8031c3fc
...@@ -6,3 +6,4 @@ composer.lock ...@@ -6,3 +6,4 @@ composer.lock
*.sublime-project *.sublime-project
*.sublime-workspace *.sublime-workspace
*.project *.project
.idea/
language: php language: php
php: php:
- 5.4
- 5.5 - 5.5
- 5.6 - 5.6
......
...@@ -10,9 +10,11 @@ An Eloquent model and Query builder with support for MongoDB, using the original ...@@ -10,9 +10,11 @@ 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. 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: 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:
```php ```php
$this->embedsMany('Book', '_books'); $this->embedsMany('Book', '_books');
``` ```
Read the full changelog at https://github.com/jenssegers/laravel-mongodb/releases/tag/v2.0.0 Read the full changelog at https://github.com/jenssegers/laravel-mongodb/releases/tag/v2.0.0
Installation Installation
...@@ -21,23 +23,30 @@ Installation ...@@ -21,23 +23,30 @@ Installation
Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongo.installation.php 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: Install using composer:
```json ```json
composer require jenssegers/mongodb composer require jenssegers/mongodb
``` ```
Add the service provider in `app/config/app.php`: Add the service provider in `app/config/app.php`:
```php ```php
'Jenssegers\Mongodb\MongodbServiceProvider', '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. 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 Configuration
------------- -------------
Change your default database connection name in `app/config/database.php`: Change your default database connection name in `app/config/database.php`:
```php ```php
'default' => 'mongodb', 'default' => 'mongodb',
``` ```
And add a new mongodb connection: And add a new mongodb connection:
```php ```php
'mongodb' => array( 'mongodb' => array(
'driver' => 'mongodb', 'driver' => 'mongodb',
...@@ -48,7 +57,9 @@ And add a new mongodb connection: ...@@ -48,7 +57,9 @@ And add a new mongodb connection:
'database' => 'database' 'database' => 'database'
), ),
``` ```
You can connect to multiple servers or replica sets with the following configuration: You can connect to multiple servers or replica sets with the following configuration:
```php ```php
'mongodb' => array( 'mongodb' => array(
'driver' => 'mongodb', 'driver' => 'mongodb',
...@@ -60,16 +71,20 @@ You can connect to multiple servers or replica sets with the following configura ...@@ -60,16 +71,20 @@ You can connect to multiple servers or replica sets with the following configura
'options' => array('replicaSet' => 'replicaSetName') 'options' => array('replicaSet' => 'replicaSetName')
), ),
``` ```
Eloquent Eloquent
-------- --------
This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections. This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
class User extends Eloquent {} class User extends Eloquent {}
``` ```
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: 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 ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -79,7 +94,9 @@ class User extends Eloquent { ...@@ -79,7 +94,9 @@ class User extends Eloquent {
} }
``` ```
**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. **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 ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -89,37 +106,47 @@ class MyModel extends Eloquent { ...@@ -89,37 +106,47 @@ class MyModel extends Eloquent {
} }
``` ```
Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent Everything else works just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent
### Optional: Alias ### 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`: You may also register an alias for the MongoDB model by adding the following to the alias array in `app/config/app.php`:
```php ```php
'Moloquent' => 'Jenssegers\Mongodb\Model', 'Moloquent' => 'Jenssegers\Mongodb\Model',
``` ```
This will allow you to use the registered alias like: This will allow you to use the registered alias like:
```php ```php
class MyModel extends Moloquent {} class MyModel extends Moloquent {}
``` ```
Query Builder 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. 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.
```php ```php
$users = DB::collection('users')->get(); $users = DB::collection('users')->get();
$user = DB::collection('users')->where('name', 'John')->first(); $user = DB::collection('users')->where('name', 'John')->first();
``` ```
If you did not change your default database connection, you will need to specify it when querying. If you did not change your default database connection, you will need to specify it when querying.
```php ```php
$user = DB::connection('mongodb')->collection('users')->get(); $user = DB::connection('mongodb')->collection('users')->get();
``` ```
Read more about the query builder on http://laravel.com/docs/queries Read more about the query builder on http://laravel.com/docs/queries
Schema Schema
------ ------
The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes:
```php ```php
Schema::create('users', function($collection) Schema::create('users', function($collection)
{ {
...@@ -128,6 +155,7 @@ Schema::create('users', function($collection) ...@@ -128,6 +155,7 @@ Schema::create('users', function($collection)
$collection->unique('email'); $collection->unique('email');
}); });
``` ```
Supported operations are: Supported operations are:
- create and drop - create and drop
...@@ -145,9 +173,11 @@ Extensions ...@@ -145,9 +173,11 @@ Extensions
### Auth ### Auth
If you want to use Laravel's native Auth functionality, register this included service provider: If you want to use Laravel's native Auth functionality, register this included service provider:
```php ```php
'Jenssegers\Mongodb\Auth\ReminderServiceProvider', 'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',
``` ```
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. 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 ### Sentry
...@@ -166,13 +196,16 @@ Troubleshooting ...@@ -166,13 +196,16 @@ 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. 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: To check if you have installed the driver correctly, run the following command:
```sh ```sh
$ php -i | grep 'Mongo' $ php -i | grep 'Mongo'
MongoDB Support => enabled MongoDB Support => enabled
``` ```
#### Argument 2 passed to Illuminate\Database\Query\Builder::__construct() must be an instance of Illuminate\Database\Query\Grammars\Grammar, null given #### 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: 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:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -182,66 +215,92 @@ class User extends Eloquent { ...@@ -182,66 +215,92 @@ class User extends Eloquent {
} }
``` ```
Examples Examples
-------- --------
### Basic Usage ### Basic Usage
**Retrieving All Models** **Retrieving All Models**
```php ```php
$users = User::all(); $users = User::all();
``` ```
**Retrieving A Record By Primary Key** **Retrieving A Record By Primary Key**
```php ```php
$user = User::find('517c43667db388101e00000f'); $user = User::find('517c43667db388101e00000f');
``` ```
**Wheres** **Wheres**
```php ```php
$users = User::where('votes', '>', 100)->take(10)->get(); $users = User::where('votes', '>', 100)->take(10)->get();
``` ```
**Or Statements** **Or Statements**
```php ```php
$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get(); $users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();
``` ```
**And Statements** **And Statements**
```php ```php
$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get(); $users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();
``` ```
**Using Where In With An Array** **Using Where In With An Array**
```php ```php
$users = User::whereIn('age', array(16, 18, 20))->get(); $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. 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** **Using Where Between**
```php ```php
$users = User::whereBetween('votes', array(1, 100))->get(); $users = User::whereBetween('votes', array(1, 100))->get();
``` ```
**Where null** **Where null**
```php ```php
$users = User::whereNull('updated_at')->get(); $users = User::whereNull('updated_at')->get();
``` ```
**Order By** **Order By**
```php ```php
$users = User::orderBy('name', 'desc')->get(); $users = User::orderBy('name', 'desc')->get();
``` ```
**Offset & Limit** **Offset & Limit**
```php ```php
$users = User::skip(10)->take(5)->get(); $users = User::skip(10)->take(5)->get();
``` ```
**Distinct** **Distinct**
Distinct requires a field for which to return the distinct values. Distinct requires a field for which to return the distinct values.
```php ```php
$users = User::distinct()->get(array('name')); $users = User::distinct()->get(array('name'));
// or // or
$users = User::distinct('name')->get(); $users = User::distinct('name')->get();
``` ```
Distinct can be combined with **where**: Distinct can be combined with **where**:
```php ```php
$users = User::where('active', true)->distinct('name')->get(); $users = User::where('active', true)->distinct('name')->get();
``` ```
**Advanced Wheres** **Advanced Wheres**
```php ```php
$users = User::where('name', '=', 'John')->orWhere(function($query) $users = User::where('name', '=', 'John')->orWhere(function($query)
{ {
...@@ -250,15 +309,19 @@ $users = User::where('name', '=', 'John')->orWhere(function($query) ...@@ -250,15 +309,19 @@ $users = User::where('name', '=', 'John')->orWhere(function($query)
}) })
->get(); ->get();
``` ```
**Group By** **Group By**
Selected columns that are not grouped will be aggregated with the $last function. Selected columns that are not grouped will be aggregated with the $last function.
```php ```php
$users = Users::groupBy('title')->get(array('title', 'name')); $users = Users::groupBy('title')->get(array('title', 'name'));
``` ```
**Aggregation** **Aggregation**
*Aggregations are only available for MongoDB versions greater than 2.2.* *Aggregations are only available for MongoDB versions greater than 2.2.*
```php ```php
$total = Order::count(); $total = Order::count();
$price = Order::max('price'); $price = Order::max('price');
...@@ -266,44 +329,57 @@ $price = Order::min('price'); ...@@ -266,44 +329,57 @@ $price = Order::min('price');
$price = Order::avg('price'); $price = Order::avg('price');
$total = Order::sum('price'); $total = Order::sum('price');
``` ```
Aggregations can be combined with **where**: Aggregations can be combined with **where**:
```php ```php
$sold = Orders::where('sold', true)->sum('price'); $sold = Orders::where('sold', true)->sum('price');
``` ```
**Like** **Like**
```php ```php
$user = Comment::where('body', 'like', '%spam%')->get(); $user = Comment::where('body', 'like', '%spam%')->get();
``` ```
**Incrementing or decrementing a value of a column** **Incrementing or decrementing a value of a column**
Perform increments or decrements (default 1) on specified attributes: Perform increments or decrements (default 1) on specified attributes:
```php ```php
User::where('name', 'John Doe')->increment('age'); User::where('name', 'John Doe')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50); User::where('name', 'Jaques')->decrement('weight', 50);
``` ```
The number of updated objects is returned: The number of updated objects is returned:
```php ```php
$count = User->increment('age'); $count = User->increment('age');
``` ```
You may also specify additional columns to update: You may also specify additional columns to update:
```php ```php
User::where('age', '29')->increment('age', 1, array('group' => 'thirty something')); User::where('age', '29')->increment('age', 1, array('group' => 'thirty something'));
User::where('bmi', 30)->decrement('bmi', 1, array('category' => 'overweight')); User::where('bmi', 30)->decrement('bmi', 1, array('category' => 'overweight'));
``` ```
**Soft deleting** **Soft deleting**
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: 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 ```php
use Jenssegers\Mongodb\Eloquent\SoftDeletingTrait; use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class User extends Eloquent { class User extends Eloquent {
use SoftDeletingTrait; use SoftDeletes;
protected $dates = ['deleted_at']; protected $dates = ['deleted_at'];
} }
``` ```
For more information check http://laravel.com/docs/eloquent#soft-deleting For more information check http://laravel.com/docs/eloquent#soft-deleting
### MongoDB specific operators ### MongoDB specific operators
...@@ -311,47 +387,63 @@ For more information check http://laravel.com/docs/eloquent#soft-deleting ...@@ -311,47 +387,63 @@ For more information check http://laravel.com/docs/eloquent#soft-deleting
**Exists** **Exists**
Matches documents that have the specified field. Matches documents that have the specified field.
```php ```php
User::where('age', 'exists', true)->get(); User::where('age', 'exists', true)->get();
``` ```
**All** **All**
Matches arrays that contain all elements specified in the query. Matches arrays that contain all elements specified in the query.
```php ```php
User::where('roles', 'all', array('moderator', 'author'))->get(); User::where('roles', 'all', array('moderator', 'author'))->get();
``` ```
**Size** **Size**
Selects documents if the array field is a specified size. Selects documents if the array field is a specified size.
```php ```php
User::where('tags', 'size', 3)->get(); User::where('tags', 'size', 3)->get();
``` ```
**Regex** **Regex**
Selects documents where values match a specified regular expression. Selects documents where values match a specified regular expression.
```php ```php
User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get(); User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get();
``` ```
**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. **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.
```php ```php
User::where('name', 'regexp', '/.*doe/i'))->get(); User::where('name', 'regexp', '/.*doe/i'))->get();
``` ```
And the inverse: And the inverse:
```php ```php
User::where('name', 'not regexp', '/.*doe/i'))->get(); User::where('name', 'not regexp', '/.*doe/i'))->get();
``` ```
**Type** **Type**
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 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
```php ```php
User::where('age', 'type', 2)->get(); User::where('age', 'type', 2)->get();
``` ```
**Mod** **Mod**
Performs a modulo operation on the value of a field and selects documents with a specified result. Performs a modulo operation on the value of a field and selects documents with a specified result.
```php ```php
User::where('age', 'mod', array(10, 0))->get(); User::where('age', 'mod', array(10, 0))->get();
``` ```
**Where** **Where**
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_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 +453,46 @@ Matches documents that satisfy a JavaScript expression. For more information che ...@@ -361,36 +453,46 @@ Matches documents that satisfy a JavaScript expression. For more information che
Inserting, updating and deleting records works just like the original Eloquent. Inserting, updating and deleting records works just like the original Eloquent.
**Saving a new model** **Saving a new model**
```php ```php
$user = new User; $user = new User;
$user->name = 'John'; $user->name = 'John';
$user->save(); $user->save();
``` ```
You may also use the create method to save a new model in a single line: You may also use the create method to save a new model in a single line:
```php ```php
User::create(array('name' => 'John')); User::create(array('name' => 'John'));
``` ```
**Updating a model** **Updating a model**
To update a model, you may retrieve it, change an attribute, and use the save method. To update a model, you may retrieve it, change an attribute, and use the save method.
```php ```php
$user = User::first(); $user = User::first();
$user->email = 'john@foo.com'; $user->email = 'john@foo.com';
$user->save(); $user->save();
``` ```
*There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations* *There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations*
**Deleting a model** **Deleting a model**
To delete a model, simply call the delete method on the instance: To delete a model, simply call the delete method on the instance:
```php ```php
$user = User::first(); $user = User::first();
$user->delete(); $user->delete();
``` ```
Or deleting a model by its key: Or deleting a model by its key:
```php ```php
User::destroy('517c43667db388101e00000f'); User::destroy('517c43667db388101e00000f');
``` ```
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete
### Dates ### Dates
...@@ -398,6 +500,7 @@ For more information about model manipulation, check http://laravel.com/docs/elo ...@@ -398,6 +500,7 @@ 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 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: Example:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -407,10 +510,13 @@ class User extends Eloquent { ...@@ -407,10 +510,13 @@ class User extends Eloquent {
} }
``` ```
Which allows you to execute queries like: Which allows you to execute queries like:
```php ```php
$users = User::where('birthday', '>', new DateTime('-18 years'))->get(); $users = User::where('birthday', '>', new DateTime('-18 years'))->get();
``` ```
### Relations ### Relations
Supported relations are: Supported relations are:
...@@ -421,6 +527,7 @@ Supported relations are: ...@@ -421,6 +527,7 @@ Supported relations are:
- belongsToMany - belongsToMany
Example: Example:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -433,7 +540,9 @@ class User extends Eloquent { ...@@ -433,7 +540,9 @@ class User extends Eloquent {
} }
``` ```
And the inverse relation: And the inverse relation:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -446,7 +555,9 @@ class Item extends Eloquent { ...@@ -446,7 +555,9 @@ class Item extends Eloquent {
} }
``` ```
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`: 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`:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -460,11 +571,13 @@ class User extends Eloquent { ...@@ -460,11 +571,13 @@ class User extends Eloquent {
} }
``` ```
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 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 ### 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. 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 ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -477,15 +590,21 @@ class User extends Eloquent { ...@@ -477,15 +590,21 @@ class User extends Eloquent {
} }
``` ```
You access the embedded models through the dynamic property: You access the embedded models through the dynamic property:
```php ```php
$books = User::first()->books; $books = User::first()->books;
``` ```
The inverse relation is auto*magically* available, you don't need to define this reverse relation. The inverse relation is auto*magically* available, you don't need to define this reverse relation.
```php ```php
$user = $book->user; $user = $book->user;
``` ```
Inserting and updating embedded models works similar to the `hasMany` relation: Inserting and updating embedded models works similar to the `hasMany` relation:
```php ```php
$book = new Book(array('title' => 'A Game of Thrones')); $book = new Book(array('title' => 'A Game of Thrones'));
...@@ -495,7 +614,9 @@ $book = $user->books()->save($book); ...@@ -495,7 +614,9 @@ $book = $user->books()->save($book);
// or // or
$book = $user->books()->create(array('title' => 'A Game of Thrones')) $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): You can update embedded models using their `save` method (available since release 2.0.0):
```php ```php
$book = $user->books()->first(); $book = $user->books()->first();
...@@ -503,7 +624,9 @@ $book->title = 'A Game of Thrones'; ...@@ -503,7 +624,9 @@ $book->title = 'A Game of Thrones';
$book->save(); $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): 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 ```php
$book = $user->books()->first(); $book = $user->books()->first();
...@@ -511,16 +634,21 @@ $book->delete(); ...@@ -511,16 +634,21 @@ $book->delete();
// or // or
$user->books()->destroy($book); $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: 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 ```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: 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:
```php ```php
return $this->embedsMany('Book', 'local_key'); 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: 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) - where($key, $operator, $value)
...@@ -534,14 +662,17 @@ Embedded relations will return a Collection of embedded items instead of a query ...@@ -534,14 +662,17 @@ Embedded relations will return a Collection of embedded items instead of a query
- skip($value) - skip($value)
This allows you to execute simple queries on the collection results: This allows you to execute simple queries on the collection results:
```php ```php
$books = $user->books()->where('rating', '>', 5)->orderBy('title')->get(); $books = $user->books()->where('rating', '>', 5)->orderBy('title')->get();
``` ```
**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. **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 ### EmbedsOne Relations
The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model. The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -554,11 +685,15 @@ class Book extends Eloquent { ...@@ -554,11 +685,15 @@ class Book extends Eloquent {
} }
``` ```
You access the embedded models through the dynamic property: You access the embedded models through the dynamic property:
```php ```php
$author = Book::first()->author; $author = Book::first()->author;
``` ```
Inserting and updating embedded models works similar to the `hasOne` relation: Inserting and updating embedded models works similar to the `hasOne` relation:
```php ```php
$author = new Author(array('name' => 'John Doe')); $author = new Author(array('name' => 'John Doe'));
...@@ -568,23 +703,29 @@ $author = $book->author()->save($author); ...@@ -568,23 +703,29 @@ $author = $book->author()->save($author);
// or // or
$author = $book->author()->create(array('name' => 'John Doe')); $author = $book->author()->create(array('name' => 'John Doe'));
``` ```
You can update the embedded model using the `save` method (available since release 2.0.0): You can update the embedded model using the `save` method (available since release 2.0.0):
```php ```php
$author = $book->author; $author = $book->author;
$author->name = 'Jane Doe'; $author->name = 'Jane Doe';
$author->save(); $author->save();
``` ```
You can replace the embedded model with a new model like this: You can replace the embedded model with a new model like this:
```php ```php
$newAuthor = new Author(array('name' => 'Jane Doe')); $newAuthor = new Author(array('name' => 'Jane Doe'));
$book->author()->save($newAuthor); $book->author()->save($newAuthor);
``` ```
### MySQL Relations ### 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. 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: Example SQL-based User model:
```php ```php
use Jenssegers\Eloquent\Model as Eloquent; use Jenssegers\Eloquent\Model as Eloquent;
...@@ -599,7 +740,9 @@ class User extends Eloquent { ...@@ -599,7 +740,9 @@ class User extends Eloquent {
} }
``` ```
And the Mongodb-based Message model: And the Mongodb-based Message model:
```php ```php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
...@@ -614,13 +757,17 @@ class Message extends Eloquent { ...@@ -614,13 +757,17 @@ class Message extends Eloquent {
} }
``` ```
### Raw Expressions ### Raw Expressions
These expressions will be injected directly into the query. These expressions will be injected directly into the query.
```php ```php
User::whereRaw(array('age' => array('$gt' => 30, '$lt' => 40)))->get(); User::whereRaw(array('age' => array('$gt' => 30, '$lt' => 40)))->get();
``` ```
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. 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.
```php ```php
// Returns a collection of User models. // Returns a collection of User models.
$models = User::raw(function($collection) $models = User::raw(function($collection)
...@@ -634,77 +781,102 @@ $cursor = DB::collection('users')->raw(function($collection) ...@@ -634,77 +781,102 @@ $cursor = DB::collection('users')->raw(function($collection)
return $collection->find(); return $collection->find();
}); });
``` ```
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible: Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible:
```php ```php
$model = User::raw()->findOne(array('age' => array('$lt' => 18))); $model = User::raw()->findOne(array('age' => array('$lt' => 18)));
``` ```
The internal MongoClient and MongoDB objects can be accessed like this: The internal MongoClient and MongoDB objects can be accessed like this:
```php ```php
$client = DB::getMongoClient(); $client = DB::getMongoClient();
$db = DB::getMongoDB(); $db = DB::getMongoDB();
``` ```
### MongoDB specific operations ### MongoDB specific operations
**Cursor timeout** **Cursor timeout**
To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor: To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor:
```php ```php
DB::collection('users')->timeout(-1)->get(); DB::collection('users')->timeout(-1)->get();
``` ```
**Upsert** **Upsert**
Update or insert a document. Additional options for the update method are passed directly to the native update method. Update or insert a document. Additional options for the update method are passed directly to the native update method.
```php ```php
DB::collection('users')->where('name', 'John') DB::collection('users')->where('name', 'John')
->update($data, array('upsert' => true)); ->update($data, array('upsert' => true));
``` ```
**Projections** **Projections**
You can apply projections to your queries using the `project` method. You can apply projections to your queries using the `project` method.
```php ```php
DB::collection('items')->project(array('tags' => array('$slice' => 1)))->get(); DB::collection('items')->project(array('tags' => array('$slice' => 1)))->get();
``` ```
**Push** **Push**
Add an items to an array. Add an items to an array.
```php ```php
DB::collection('users')->where('name', 'John')->push('items', 'boots'); DB::collection('users')->where('name', 'John')->push('items', 'boots');
DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));
``` ```
If you don't want duplicate items, set the third parameter to `true`: If you don't want duplicate items, set the third parameter to `true`:
```php ```php
DB::collection('users')->where('name', 'John')->push('items', 'boots', true); DB::collection('users')->where('name', 'John')->push('items', 'boots', true);
``` ```
**Pull** **Pull**
Remove an item from an array. Remove an item from an array.
```php ```php
DB::collection('users')->where('name', 'John')->pull('items', 'boots'); DB::collection('users')->where('name', 'John')->pull('items', 'boots');
DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John')); DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));
``` ```
**Unset** **Unset**
Remove one or more fields from a document. Remove one or more fields from a document.
```php ```php
DB::collection('users')->where('name', 'John')->unset('note'); DB::collection('users')->where('name', 'John')->unset('note');
``` ```
You can also perform an unset on a model. You can also perform an unset on a model.
```php ```php
$user = User::where('name', 'John')->first(); $user = User::where('name', 'John')->first();
$user->unset('note'); $user->unset('note');
``` ```
### Query Caching ### Query Caching
You may easily cache the results of a query using the remember method: You may easily cache the results of a query using the remember method:
```php ```php
$users = User::remember(10)->get(); $users = User::remember(10)->get();
``` ```
*From: http://laravel.com/docs/queries#caching-queries* *From: http://laravel.com/docs/queries#caching-queries*
### Query Logging ### 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: 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:
```php ```php
DB::connection()->disableQueryLog(); DB::connection()->disableQueryLog();
``` ```
*From: http://laravel.com/docs/database#query-logging* *From: http://laravel.com/docs/database#query-logging*
...@@ -10,14 +10,14 @@ ...@@ -10,14 +10,14 @@
], ],
"license" : "MIT", "license" : "MIT",
"require": { "require": {
"php": ">=5.4.0", "php": ">=5.5.0",
"illuminate/support": "4.2.*", "illuminate/support": "5.0.*",
"illuminate/container": "4.2.*", "illuminate/container": "5.0.*",
"illuminate/database": "4.2.*", "illuminate/database": "5.0.*",
"illuminate/events": "4.2.*" "illuminate/events": "5.0.*"
}, },
"require-dev": { "require-dev": {
"orchestra/testbench": "2.2.*", "orchestra/testbench": "3.0.*",
"mockery/mockery": "*", "mockery/mockery": "*",
"satooshi/php-coveralls": "*" "satooshi/php-coveralls": "*"
}, },
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
use DateTime; use DateTime;
use MongoDate; use MongoDate;
class DatabaseReminderRepository extends \Illuminate\Auth\Reminders\DatabaseReminderRepository { class DatabaseTokenRepository extends \Illuminate\Auth\Passwords\DatabaseTokenRepository {
/** /**
* Build the record payload for the table. * Build the record payload for the table.
...@@ -14,36 +14,28 @@ class DatabaseReminderRepository extends \Illuminate\Auth\Reminders\DatabaseRemi ...@@ -14,36 +14,28 @@ class DatabaseReminderRepository extends \Illuminate\Auth\Reminders\DatabaseRemi
*/ */
protected function getPayload($email, $token) protected function getPayload($email, $token)
{ {
return array('email' => $email, 'token' => $token, 'created_at' => new MongoDate); return ['email' => $email, 'token' => $token, 'created_at' => new MongoDate];
} }
/** /**
* Determine if the reminder has expired. * Determine if the token has expired.
* *
* @param object $reminder * @param array $token
* @return bool * @return bool
*/ */
protected function reminderExpired($reminder) protected function tokenExpired($token)
{ {
// Convert MongoDate to a date string. // Convert MongoDate to a date string.
if ($reminder['created_at'] instanceof MongoDate) if ($token['created_at'] instanceof MongoDate)
{ {
$date = new DateTime; $date = new DateTime;
$date->setTimestamp($reminder['created_at']->sec); $date->setTimestamp($token['created_at']->sec);
$reminder['created_at'] = $date->format('Y-m-d H:i:s'); $token['created_at'] = $date->format('Y-m-d H:i:s');
} }
// Convert DateTime to a date string (backwards compatibility). return parent::tokenExpired($token);
elseif (is_array($reminder['created_at']))
{
$date = DateTime::__set_state($reminder['created_at']);
$reminder['created_at'] = $date->format('Y-m-d H:i:s');
}
return parent::reminderExpired($reminder);
} }
} }
<?php namespace Jenssegers\Mongodb\Auth; <?php namespace Jenssegers\Mongodb\Auth;
use Jenssegers\Mongodb\Auth\DatabaseReminderRepository as DbRepository; use Jenssegers\Mongodb\Auth\DatabaseTokenRepository as DbRepository;
class ReminderServiceProvider extends \Illuminate\Auth\Reminders\ReminderServiceProvider { class PasswordResetServiceProvider extends \Illuminate\Auth\Passwords\PasswordResetServiceProvider {
/** /**
* Register the reminder repository implementation. * Register the token repository implementation.
* *
* @return void * @return void
*/ */
protected function registerReminderRepository() protected function registerTokenRepository()
{ {
$this->app->bindShared('auth.reminder.repository', function($app) $this->app->singleton('auth.password.tokens', function($app)
{ {
$connection = $app['db']->connection(); $connection = $app['db']->connection();
// The database token repository is an implementation of the token repository
// The database reminder repository is an implementation of the reminder repo
// interface, and is responsible for the actual storing of auth tokens and // interface, and is responsible for the actual storing of auth tokens and
// their e-mail addresses. We will inject this table and hash key to it. // their e-mail addresses. We will inject this table and hash key to it.
$table = $app['config']['auth.reminder.table']; $table = $app['config']['auth.password.table'];
$key = $app['config']['app.key']; $key = $app['config']['app.key'];
$expire = $app['config']->get('auth.password.expire', 60);
$expire = $app['config']->get('auth.reminder.expire', 60);
return new DbRepository($connection, $table, $key, $expire); return new DbRepository($connection, $table, $key, $expire);
}); });
} }
......
<?php namespace Jenssegers\Mongodb\Eloquent; <?php namespace Jenssegers\Mongodb\Eloquent;
trait SoftDeletingTrait { trait SoftDeletes {
use \Illuminate\Database\Eloquent\SoftDeletingTrait; use \Illuminate\Database\Eloquent\SoftDeletes;
/** /**
* Get the fully qualified "deleted at" column. * Get the fully qualified "deleted at" column.
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
use MongoId; use MongoId;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Pagination\Paginator;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Pagination\LengthAwarePaginator;
class EmbedsMany extends EmbedsOneOrMany { class EmbedsMany extends EmbedsOneOrMany {
...@@ -275,17 +275,19 @@ class EmbedsMany extends EmbedsOneOrMany { ...@@ -275,17 +275,19 @@ class EmbedsMany extends EmbedsOneOrMany {
*/ */
public function paginate($perPage = null, $columns = array('*')) public function paginate($perPage = null, $columns = array('*'))
{ {
$page = Paginator::resolveCurrentPage();
$perPage = $perPage ?: $this->related->getPerPage(); $perPage = $perPage ?: $this->related->getPerPage();
$paginator = $this->related->getConnection()->getPaginator();
$results = $this->getEmbedded(); $results = $this->getEmbedded();
$start = ($paginator->getCurrentPage() - 1) * $perPage; $total = count($results);
$start = ($page - 1) * $perPage;
$sliced = array_slice($results, $start, $perPage); $sliced = array_slice($results, $start, $perPage);
return $paginator->make($sliced, count($results), $perPage); return new LengthAwarePaginator($sliced, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath()
]);
} }
/** /**
......
...@@ -383,7 +383,7 @@ abstract class EmbedsOneOrMany extends Relation { ...@@ -383,7 +383,7 @@ abstract class EmbedsOneOrMany extends Relation {
* *
* @return string * @return string
*/ */
protected function getQualifiedParentKeyName() public function getQualifiedParentKeyName()
{ {
if ($parentRelation = $this->getParentRelation()) if ($parentRelation = $this->getParentRelation())
{ {
......
<?php <?php
use Illuminate\Auth\Passwords\PasswordBroker;
class AuthTest extends TestCase { class AuthTest extends TestCase {
public function tearDown() public function tearDown()
...@@ -23,7 +25,10 @@ class AuthTest extends TestCase { ...@@ -23,7 +25,10 @@ class AuthTest extends TestCase {
public function testRemind() public function testRemind()
{ {
$mailer = Mockery::mock('Illuminate\Mail\Mailer'); $mailer = Mockery::mock('Illuminate\Mail\Mailer');
$this->app->instance('mailer', $mailer); $tokens = $this->app->make('auth.password.tokens');
$users = $this->app['auth']->driver()->getProvider();
$broker = new PasswordBroker($tokens, $users, $mailer, '');
$user = User::create(array( $user = User::create(array(
'name' => 'John Doe', 'name' => 'John Doe',
...@@ -32,10 +37,10 @@ class AuthTest extends TestCase { ...@@ -32,10 +37,10 @@ class AuthTest extends TestCase {
)); ));
$mailer->shouldReceive('send')->once(); $mailer->shouldReceive('send')->once();
Password::remind(array('email' => 'john@doe.com')); $broker->sendResetLink(array('email' => 'john@doe.com'));
$this->assertEquals(1, DB::collection('password_reminders')->count()); $this->assertEquals(1, DB::collection('password_resets')->count());
$reminder = DB::collection('password_reminders')->first(); $reminder = DB::collection('password_resets')->first();
$this->assertEquals('john@doe.com', $reminder['email']); $this->assertEquals('john@doe.com', $reminder['email']);
$this->assertNotNull($reminder['token']); $this->assertNotNull($reminder['token']);
$this->assertInstanceOf('MongoDate', $reminder['created_at']); $this->assertInstanceOf('MongoDate', $reminder['created_at']);
...@@ -47,49 +52,14 @@ class AuthTest extends TestCase { ...@@ -47,49 +52,14 @@ class AuthTest extends TestCase {
'token' => $reminder['token'] 'token' => $reminder['token']
); );
$response = Password::reset($credentials, function($user, $password) $response = $broker->reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
$this->assertEquals('reminders.reset', $response);
$this->assertEquals(0, DB::collection('password_reminders')->count());
}
public function testDeprecatedRemind()
{
$mailer = Mockery::mock('Illuminate\Mail\Mailer');
$this->app->instance('mailer', $mailer);
$user = User::create(array(
'name' => 'John Doe',
'email' => 'john@doe.com',
'password' => Hash::make('foobar')
));
$mailer->shouldReceive('send')->once();
Password::remind(array('email' => 'john@doe.com'));
DB::collection('password_reminders')->update(array('created_at' => new DateTime));
$reminder = DB::collection('password_reminders')->first();
$this->assertTrue(is_array($reminder['created_at']));
$credentials = array(
'email' => 'john@doe.com',
'password' => 'foobar',
'password_confirmation' => 'foobar',
'token' => $reminder['token']
);
$response = Password::reset($credentials, function($user, $password)
{ {
$user->password = Hash::make($password); $user->password = bcrypt($password);
$user->save(); $user->save();
}); });
$this->assertEquals('reminders.reset', $response); $this->assertEquals('passwords.reset', $response);
$this->assertEquals(0, DB::collection('password_reminders')->count()); $this->assertEquals(0, DB::collection('password_resets')->count());
} }
} }
<?php
class CacheTest extends TestCase {
public function tearDown()
{
User::truncate();
Cache::forget('db.users');
}
public function testCache()
{
User::create(array('name' => 'John Doe', 'age' => 35, 'title' => 'admin'));
User::create(array('name' => 'Jane Doe', 'age' => 33, 'title' => 'admin'));
User::create(array('name' => 'Harry Hoe', 'age' => 13, 'title' => 'user'));
$users = DB::collection('users')->where('age', '>', 10)->remember(10)->get();
$this->assertEquals(3, count($users));
$users = DB::collection('users')->where('age', '>', 10)->getCached();
$this->assertEquals(3, count($users));
$users = User::where('age', '>', 10)->remember(10, 'db.users')->get();
$this->assertEquals(3, count($users));
$users = Cache::get('db.users');
$this->assertEquals(3, count($users));
}
}
...@@ -64,6 +64,8 @@ class ConnectionTest extends TestCase { ...@@ -64,6 +64,8 @@ class ConnectionTest extends TestCase {
public function testQueryLog() public function testQueryLog()
{ {
DB::enableQueryLog();
$this->assertEquals(0, count(DB::getQueryLog())); $this->assertEquals(0, count(DB::getQueryLog()));
DB::collection('items')->get(); DB::collection('items')->get();
......
...@@ -746,7 +746,7 @@ class EmbeddedRelationsTest extends TestCase { ...@@ -746,7 +746,7 @@ class EmbeddedRelationsTest extends TestCase {
$results = $user->addresses()->paginate(2); $results = $user->addresses()->paginate(2);
$this->assertEquals(2, $results->count()); $this->assertEquals(2, $results->count());
$this->assertEquals(3, $results->getTotal()); $this->assertEquals(3, $results->total());
} }
} }
...@@ -24,11 +24,6 @@ class QueryTest extends TestCase { ...@@ -24,11 +24,6 @@ class QueryTest extends TestCase {
self::$started = true; self::$started = true;
} }
public static function tearDownAfterClass()
{
User::truncate();
}
public function testWhere() public function testWhere()
{ {
$users = User::where('age', 35)->get(); $users = User::where('age', 35)->get();
...@@ -316,4 +311,14 @@ class QueryTest extends TestCase { ...@@ -316,4 +311,14 @@ class QueryTest extends TestCase {
$this->assertNull($results->first()->title); $this->assertNull($results->first()->title);
} }
/*
* FIXME: This should be done in tearDownAfterClass, but something doens't work:
* https://travis-ci.org/duxet/laravel-mongodb/jobs/46657530
*/
public function testTruncate()
{
User::truncate();
$this->assertEquals(0, User::count());
}
} }
...@@ -5,13 +5,14 @@ class TestCase extends Orchestra\Testbench\TestCase { ...@@ -5,13 +5,14 @@ class TestCase extends Orchestra\Testbench\TestCase {
/** /**
* Get package providers. * Get package providers.
* *
* @param \Illuminate\Foundation\Application $app
* @return array * @return array
*/ */
protected function getPackageProviders() protected function getPackageProviders($app)
{ {
return array( return array(
'Jenssegers\Mongodb\MongodbServiceProvider', 'Jenssegers\Mongodb\MongodbServiceProvider',
'Jenssegers\Mongodb\Auth\ReminderServiceProvider', 'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',
); );
} }
...@@ -36,7 +37,7 @@ class TestCase extends Orchestra\Testbench\TestCase { ...@@ -36,7 +37,7 @@ class TestCase extends Orchestra\Testbench\TestCase {
$app['config']->set('database.connections.mysql', $config['connections']['mysql']); $app['config']->set('database.connections.mysql', $config['connections']['mysql']);
$app['config']->set('database.connections.mongodb', $config['connections']['mongodb']); $app['config']->set('database.connections.mongodb', $config['connections']['mongodb']);
// overwrite cache configuration $app['config']->set('auth.model', 'User');
$app['config']->set('cache.driver', 'array'); $app['config']->set('cache.driver', 'array');
} }
......
<?php <?php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
use Jenssegers\Mongodb\Eloquent\SoftDeletingTrait; use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class Soft extends Eloquent { class Soft extends Eloquent {
use SoftDeletingTrait; use SoftDeletes;
protected $collection = 'soft'; protected $collection = 'soft';
protected static $unguarded = true; protected static $unguarded = true;
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
use Illuminate\Auth\UserTrait; use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\UserInterface; use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Reminders\RemindableInterface; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements UserInterface, RemindableInterface { class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract {
use UserTrait, RemindableTrait; use Authenticatable, CanResetPassword;
protected $dates = array('birthday', 'entry.date'); protected $dates = array('birthday', 'entry.date');
protected static $unguarded = true; protected static $unguarded = true;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment