Unverified Commit 343e7bbf authored by Stephan de Souza's avatar Stephan de Souza Committed by GitHub

Merge branch 'master' into fix-hasmany

parents bf4fe793 20fd7b02
name: CI
on:
push:
branches:
tags:
pull_request:
jobs:
build:
runs-on: ${{matrix.os}}
strategy:
matrix:
php: ['7.1', '7.2', '7.3', '7.4']
os: ['ubuntu-latest']
mongodb: ['3.6', '4.0', '4.2']
services:
mongo:
image: mongo:${{ matrix.mongodb }}
ports:
- 27017:27017
mysql:
image: mysql:5.7
ports:
- 3307:3306
env:
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
MYSQL_DATABASE: 'unittest'
MYSQL_ROOT_PASSWORD:
name: PHP v${{ matrix.php }} with Mongo v${{ matrix.mongodb }}
steps:
- uses: actions/checkout@v1
- name: Show PHP version
run: php${{ matrix.php }} -v && composer -V
- name: Show Docker version
run: if [[ "$DEBUG" == "true" ]]; then docker version && env; fi
env:
DEBUG: ${{secrets.DEBUG}}
- name: Download Composer cache dependencies from cache
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache Composer dependencies
uses: actions/cache@v1
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ matrix.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ matrix.os }}-composer-
- name: Install dependencies
run: |
composer install --no-interaction
- name: Run tests
run: |
./vendor/bin/phpunit --coverage-clover coverage.xml
env:
MONGO_HOST: 0.0.0.0
MYSQL_HOST: 0.0.0.0
MYSQL_PORT: 3307
- name: Send coveralls
run: vendor/bin/coveralls coverage.xml
env:
COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: false
preset: laravel
language: minimal
matrix:
include:
- name: "7.1"
env: PHP_VERSION=7.1
- name: "7.2"
env: PHP_VERSION=7.2
- name: "7.3"
env: PHP_VERSION=7.3
services:
- docker
cache:
directories:
- $HOME/.composer/cache
install:
- docker version
- sudo pip install docker-compose
- docker-compose version
- docker-compose build --build-arg PHP_VERSION=${PHP_VERSION}
- docker-compose run --rm tests composer install --no-interaction
script:
- docker-compose run --rm tests ./vendor/bin/phpunit --coverage-clover ./clover.xml
Laravel MongoDB Laravel MongoDB
=============== ===============
[![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](http://img.shields.io/travis/jenssegers/laravel-mongodb.svg)](https://travis-ci.org/jenssegers/laravel-mongodb) [![Coverage Status](http://img.shields.io/coveralls/jenssegers/laravel-mongodb.svg)](https://coveralls.io/r/jenssegers/laravel-mongodb?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) [![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb)
[![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb)
An Eloquent model and Query builder with support for MongoDB, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.* [![Build Status](https://img.shields.io/github/workflow/status/jenssegers/laravel-mongodb/CI)](https://github.com/jenssegers/laravel-mongodb/actions)
[![codecov](https://codecov.io/gh/jenssegers/laravel-mongodb/branch/master/graph/badge.svg)](https://codecov.io/gh/jenssegers/laravel-mongodb/branch/master)
Table of contents [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers)
-----------------
* [Installation](#installation) This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.*
* [Upgrading](#upgrading)
* [Configuration](#configuration) - [Laravel MongoDB](#laravel-mongodb)
* [Eloquent](#eloquent) - [Installation](#installation)
* [Optional: Alias](#optional-alias) - [Laravel version Compatibility](#laravel-version-compatibility)
* [Query Builder](#query-builder) - [Laravel](#laravel)
* [Schema](#schema) - [Lumen](#lumen)
* [Extensions](#extensions) - [Non-Laravel projects](#non-laravel-projects)
* [Troubleshooting](#troubleshooting) - [Testing](#testing)
* [Examples](#examples) - [Configuration](#configuration)
- [Eloquent](#eloquent)
- [Extending the base model](#extending-the-base-model)
- [Soft Deletes](#soft-deletes)
- [Dates](#dates)
- [Basic Usage](#basic-usage)
- [MongoDB-specific operators](#mongodb-specific-operators)
- [MongoDB-specific Geo operations](#mongodb-specific-geo-operations)
- [Inserts, updates and deletes](#inserts-updates-and-deletes)
- [MongoDB specific operations](#mongodb-specific-operations)
- [Relationships](#relationships)
- [Basic Usage](#basic-usage-1)
- [belongsToMany and pivots](#belongstomany-and-pivots)
- [EmbedsMany Relationship](#embedsmany-relationship)
- [EmbedsOne Relationship](#embedsone-relationship)
- [Query Builder](#query-builder)
- [Basic Usage](#basic-usage-2)
- [Available operations](#available-operations)
- [Schema](#schema)
- [Basic Usage](#basic-usage-3)
- [Geospatial indexes](#geospatial-indexes)
- [Extending](#extending)
- [Cross-Database Relationships](#cross-database-relationships)
- [Authentication](#authentication)
- [Queues](#queues)
- [Upgrading](#upgrading)
- [Upgrading from version 2 to 3](#upgrading-from-version-2-to-3)
Installation Installation
------------ ------------
Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php
**WARNING**: The old mongo PHP driver is not supported anymore in versions >= 3.0.
Installation using composer:
```
composer require jenssegers/mongodb
```
### Laravel version Compatibility ### Laravel version Compatibility
Laravel | Package Laravel | Package
...@@ -45,13 +62,24 @@ composer require jenssegers/mongodb ...@@ -45,13 +62,24 @@ composer require jenssegers/mongodb
5.6.x | 3.4.x 5.6.x | 3.4.x
5.7.x | 3.4.x 5.7.x | 3.4.x
5.8.x | 3.5.x 5.8.x | 3.5.x
6.0.x | 3.6.x
And add the service provider in `config/app.php`: Install the package via Composer:
```bash
$ composer require jenssegers/mongodb
```
### Laravel
In case your Laravel version does NOT autoload the packages, add the service provider to `config/app.php`:
```php ```php
Jenssegers\Mongodb\MongodbServiceProvider::class, Jenssegers\Mongodb\MongodbServiceProvider::class,
``` ```
### Lumen
For usage with [Lumen](http://lumen.laravel.com), add the service provider in `bootstrap/app.php`. In this file, you will also need to enable Eloquent. You must however ensure that your call to `$app->withEloquent();` is **below** where you have registered the `MongodbServiceProvider`: For usage with [Lumen](http://lumen.laravel.com), add the service provider in `bootstrap/app.php`. In this file, you will also need to enable Eloquent. You must however ensure that your call to `$app->withEloquent();` is **below** where you have registered the `MongodbServiceProvider`:
```php ```php
...@@ -60,54 +88,22 @@ $app->register(Jenssegers\Mongodb\MongodbServiceProvider::class); ...@@ -60,54 +88,22 @@ $app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->withEloquent(); $app->withEloquent();
``` ```
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.
### Non-Laravel projects
For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add: For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add:
```php ```php
$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) $capsule->getDatabaseManager()->extend('mongodb', function($config, $name) {
{
$config['name'] = $name; $config['name'] = $name;
return new Jenssegers\Mongodb\Connection($config); return new Jenssegers\Mongodb\Connection($config);
}); });
``` ```
Upgrading
---------
#### Upgrading from version 2 to 3
In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait.
Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files, or your registered alias.
```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {}
```
If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package.
```php
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class User extends Eloquent {
use HybridRelations;
protected $connection = 'mysql';
}
```
Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations.
```php
$books = $user->books()->sortBy('title');
```
Testing Testing
------- -------
...@@ -119,289 +115,238 @@ docker-compose up ...@@ -119,289 +115,238 @@ docker-compose up
Configuration Configuration
------------- -------------
You can use MongoDB either as the main database, either as a side database. To do so, add a new `mongodb` connection to `config/database.php`:
Change your default database connection name in `config/database.php`:
```php
'default' => env('DB_CONNECTION', 'mongodb'),
```
And add a new mongodb connection:
```php ```php
'mongodb' => [ 'mongodb' => [
'driver' => 'mongodb', 'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'), 'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', 27017), 'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE'), 'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME'), 'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD'), 'password' => env('DB_PASSWORD', 'secret'),
'options' => [ 'options' => [
'database' => 'admin' // sets the authentication database required by mongo 3 // here you can pass more settings to the Mongo Driver Manager
] // see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters that you can use
'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+
],
], ],
``` ```
You can connect to multiple servers or replica sets with the following configuration: For multiple servers or replica set configurations, set the host to an array and specify each server host:
```php ```php
'mongodb' => [ 'mongodb' => [
'driver' => 'mongodb', 'driver' => 'mongodb',
'host' => ['server1', 'server2'], 'host' => ['server1', 'server2', ...],
'port' => env('DB_PORT', 27017), ...
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'options' => [ 'options' => [
'replicaSet' => 'replicaSetName' 'replicaSet' => 'rs0',
] ],
], ],
``` ```
Alternatively, you can use MongoDB connection string: If you wish to use a connection string instead of full key-value params, you can set it so. Check the documentation on MongoDB's URI format: https://docs.mongodb.com/manual/reference/connection-string/
```php ```php
'mongodb' => [ 'mongodb' => [
'driver' => 'mongodb', 'driver' => 'mongodb',
'dsn' => env('DB_DSN'), 'dsn' => env('DB_DSN'),
'database' => env('DB_DATABASE'), 'database' => env('DB_DATABASE', 'homestead'),
], ],
``` ```
Please refer to MongoDB official docs for its URI format: https://docs.mongodb.com/manual/reference/connection-string/
Eloquent Eloquent
-------- --------
### Extending the base model
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\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model;
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 collection 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
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
protected $collection = 'users_collection';
class Book extends 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. Just like a normal model, the MongoDB model class will know which collection to use based on the model name. For `Book`, the collection `books` will be used.
```php To change the collection, pass the `$collection` property:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class MyModel extends Eloquent {
protected $connection = 'mongodb'; ```php
use Jenssegers\Mongodb\Eloquent\Model;
class Book extends Model
{
protected $collection = 'my_books_collection';
} }
``` ```
Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent **NOTE:** MongoDB documents are automatically stored with a unique ID that is stored in the `_id` property. If you wish to use your own ID, substitute the `$primaryKey` property and set it to your own primary key attribute name.
### Optional: Alias
You may also register an alias for the MongoDB model by adding the following to the alias array in `config/app.php`:
```php ```php
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class, use Jenssegers\Mongodb\Eloquent\Model;
```
This will allow you to use the registered alias like: class Book extends Model
{
protected $primaryKey = 'id';
}
```php // Mongo will also create _id, but the 'id' property will be used for primary key actions like find().
class MyModel extends Moloquent {} Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']);
``` ```
Query Builder Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model.
-------------
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(); use Jenssegers\Mongodb\Eloquent\Model;
$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. class Book extends Model
{
```php protected $connection = 'mongodb';
$user = DB::connection('mongodb')->collection('users')->get(); }
``` ```
Read more about the query builder on http://laravel.com/docs/queries ### Soft Deletes
Schema When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record.
------
The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: To enable soft deletes for a model, apply the `Jenssegers\Mongodb\Eloquent\SoftDeletes` Trait to the model:
```php ```php
Schema::create('users', function($collection) use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class User extends Model
{ {
$collection->index('name'); use SoftDeletes;
$collection->unique('email'); protected $dates = ['deleted_at'];
}); }
``` ```
Supported operations are: For more information check [Laravel Docs about Soft Deleting](http://laravel.com/docs/eloquent#soft-deleting).
- create and drop
- collection
- hasCollection
- index and dropIndex (compound indexes supported as well)
- unique
- background, sparse, expire, geospatial (MongoDB specific)
All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. Read more about the schema builder on http://laravel.com/docs/schema
### Geospatial indexes ### Dates
Geospatial indexes are handy for querying location-based documents. They come in two forms: `2d` and `2dsphere`. Use the schema builder to add these to a collection.
To add a `2d` index: Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database.
```php ```php
Schema::create('users', function($collection) use Jenssegers\Mongodb\Eloquent\Model;
{
$collection->geospatial('name', '2d');
});
```
To add a `2dsphere` index: class User extends Model
```php
Schema::create('users', function($collection)
{ {
$collection->geospatial('name', '2dsphere'); protected $dates = ['birthday'];
}); }
``` ```
Extensions This allows you to execute queries like this:
----------
### Auth
If you want to use Laravel's native Auth functionality, register this included service provider:
```php ```php
'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider', $users = User::where(
'birthday', '>',
new DateTime('-18 years')
)->get();
``` ```
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. ### Basic Usage
### Queues
If you want to use MongoDB as your database backend, change the driver in `config/queue.php`: **Retrieving all models**
```php ```php
'connections' => [ $users = User::all();
'database' => [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
``` ```
If you want to use MongoDB to handle failed jobs, change the database in `config/queue.php`: **Retrieving a record by primary key**
```php ```php
'failed' => [ $user = User::find('517c43667db388101e00000f');
'database' => 'mongodb',
'table' => 'failed_jobs',
],
``` ```
And add the service provider in `config/app.php`: **Where**
```php ```php
Jenssegers\Mongodb\MongodbQueueServiceProvider::class, $posts =
Post::where('author.name', 'John')
->take(10)
->get();
``` ```
### Sentry **OR Statements**
If you want to use this library with [Sentry](https://cartalyst.com/manual/sentry), then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry
### 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**
```php ```php
$users = User::all(); $posts =
Post::where('votes', '>', 0)
->orWhere('is_approved', true)
->get();
``` ```
**Retrieving A Record By Primary Key** **AND statements**
```php ```php
$user = User::find('517c43667db388101e00000f'); $users =
User::where('age', '>', 18)
->where('name', '!=', 'John')
->get();
``` ```
**Wheres** **whereIn**
```php ```php
$users = User::where('votes', '>', 100)->take(10)->get(); $users = User::whereIn('age', [16, 18, 20])->get();
``` ```
**Or Statements** When using `whereNotIn` objects will be returned if the field is non-existent. Combine with `whereNotNull('age')` to leave out those documents.
```php **whereBetween**
$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();
```
**And Statements**
```php ```php
$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get(); $posts = Post::whereBetween('votes', [1, 100])->get();
``` ```
**Using Where In With An Array** **whereNull**
```php ```php
$users = User::whereIn('age', [16, 18, 20])->get(); $users = User::whereNull('age')->get();
``` ```
When using `whereNotIn` objects will be returned if the field is non existent. Combine with `whereNotNull('age')` to leave out those documents. **Advanced wheres**
**Using Where Between**
```php ```php
$users = User::whereBetween('votes', [1, 100])->get(); $users =
User::where('name', 'John')
->orWhere(function ($query) {
return $query
->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})->get();
``` ```
**Where null** **orderBy**
```php ```php
$users = User::whereNull('updated_at')->get(); $users = User::orderBy('age', 'desc')->get();
``` ```
**Order By** **Offset & Limit (skip & take)**
```php ```php
$users = User::orderBy('name', 'desc')->get(); $users =
User::skip(10)
->take(5)
->get();
``` ```
**Offset & Limit** **groupBy**
Selected columns that are not grouped will be aggregated with the `$last` function.
```php ```php
$users = User::skip(10)->take(5)->get(); $users =
Users::groupBy('title')
->get(['title', 'name']);
``` ```
**Distinct** **Distinct**
...@@ -410,45 +355,36 @@ Distinct requires a field for which to return the distinct values. ...@@ -410,45 +355,36 @@ Distinct requires a field for which to return the distinct values.
```php ```php
$users = User::distinct()->get(['name']); $users = User::distinct()->get(['name']);
// or
// Equivalent to:
$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')
**Advanced Wheres**
```php
$users = User::where('name', '=', 'John')->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get(); ->get();
``` ```
**Group By** **Like**
Selected columns that are not grouped will be aggregated with the $last function.
```php ```php
$users = Users::groupBy('title')->get(['title', 'name']); $spamComments = Comment::where('body', 'like', '%spam%')->get();
``` ```
**Aggregation** **Aggregation**
*Aggregations are only available for MongoDB versions greater than 2.2.* **Aggregations are only available for MongoDB versions greater than 2.2.x**
```php ```php
$total = Order::count(); $total = Product::count();
$price = Order::max('price'); $price = Product::max('price');
$price = Order::min('price'); $price = Product::min('price');
$price = Order::avg('price'); $price = Product::avg('price');
$total = Order::sum('price'); $total = Product::sum('price');
``` ```
Aggregations can be combined with **where**: Aggregations can be combined with **where**:
...@@ -457,28 +393,22 @@ Aggregations can be combined with **where**: ...@@ -457,28 +393,22 @@ Aggregations can be combined with **where**:
$sold = Orders::where('sold', true)->sum('price'); $sold = Orders::where('sold', true)->sum('price');
``` ```
Aggregations can be also used on subdocuments: Aggregations can be also used on sub-documents:
```php ```php
$total = Order::max('suborder.price'); $total = Order::max('suborder.price');
...
``` ```
**NOTE**: this aggreagtion only works with single subdocuments (like embedsOne) not subdocument arrays (like embedsMany) **NOTE**: This aggregation only works with single sub-documents (like `EmbedsOne`) not subdocument arrays (like `EmbedsMany`).
**Like** **Incrementing/Decrementing the value of a column**
```php
$user = Comment::where('body', 'like', '%spam%')->get();
```
**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'); Cat::where('name', 'Kitty')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50);
Car::where('name', 'Toyota')->decrement('weight', 50);
``` ```
The number of updated objects is returned: The number of updated objects is returned:
...@@ -490,29 +420,14 @@ $count = User::increment('age'); ...@@ -490,29 +420,14 @@ $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, ['group' => 'thirty something']); Cat::where('age', 3)
User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']); ->increment('age', 1, ['group' => 'Kitty Club']);
```
**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:
```php
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class User extends Eloquent {
use SoftDeletes;
protected $dates = ['deleted_at']; Car::where('weight', 300)
->decrement('weight', 100, ['latest_change' => 'carbon fiber']);
}
``` ```
For more information check http://laravel.com/docs/eloquent#soft-deleting ### MongoDB-specific operators
### MongoDB specific operators
**Exists** **Exists**
...@@ -535,7 +450,7 @@ User::where('roles', 'all', ['moderator', 'author'])->get(); ...@@ -535,7 +450,7 @@ User::where('roles', 'all', ['moderator', 'author'])->get();
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(); Post::where('tags', 'size', 3)->get();
``` ```
**Regex** **Regex**
...@@ -543,19 +458,21 @@ User::where('tags', 'size', 3)->get(); ...@@ -543,19 +458,21 @@ User::where('tags', 'size', 3)->get();
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 \MongoDB\BSON\Regex("/.*doe/i"))->get(); use MongoDB\BSON\Regex;
User::where('name', 'regex', new Regex("/.*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 MongoDB\BSON\Regex 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 `MongoDB\BSON\Regex` object.
```php ```php
User::where('name', 'regexp', '/.*doe/i'))->get(); User::where('name', 'regexp', '/.*doe/i')->get();
``` ```
And the inverse: The inverse of regexp:
```php ```php
User::where('name', 'not regexp', '/.*doe/i'))->get(); User::where('name', 'not regexp', '/.*doe/i')->get();
``` ```
**Type** **Type**
...@@ -574,245 +491,306 @@ Performs a modulo operation on the value of a field and selects documents with a ...@@ -574,245 +491,306 @@ Performs a modulo operation on the value of a field and selects documents with a
User::where('age', 'mod', [10, 0])->get(); User::where('age', 'mod', [10, 0])->get();
``` ```
**Near** ### MongoDB-specific Geo operations
**NOTE:** Specify coordinates in this order: `longitude, latitude`. **Near**
```php ```php
$users = User::where('location', 'near', [ $bars = Bar::where('location', 'near', [
'$geometry' => [ '$geometry' => [
'type' => 'Point', 'type' => 'Point',
'coordinates' => [ 'coordinates' => [
-0.1367563, -0.1367563, // longitude
51.5100913, 51.5100913, // latitude
], ],
], ],
'$maxDistance' => 50, '$maxDistance' => 50,
]); ])->get();
``` ```
**GeoWithin** **GeoWithin**
```php ```php
$users = User::where('location', 'geoWithin', [ $bars = Bar::where('location', 'geoWithin', [
'$geometry' => [ '$geometry' => [
'type' => 'Polygon', 'type' => 'Polygon',
'coordinates' => [[ 'coordinates' => [
[
-0.1450383,
51.5069158,
],
[ [
-0.1367563, [-0.1450383, 51.5069158],
51.5100913, [-0.1367563, 51.5100913],
[-0.1270247, 51.5013233],
[-0.1450383, 51.5069158],
], ],
[
-0.1270247,
51.5013233,
], ],
[
-0.1450383,
51.5069158,
], ],
]], ])->get();
],
]);
``` ```
**GeoIntersects** **GeoIntersects**
```php ```php
$locations = Location::where('location', 'geoIntersects', [ $bars = Bar::where('location', 'geoIntersects', [
'$geometry' => [ '$geometry' => [
'type' => 'LineString', 'type' => 'LineString',
'coordinates' => [ 'coordinates' => [
[ [-0.144044, 51.515215],
-0.144044, [-0.129545, 51.507864],
51.515215,
],
[
-0.129545,
51.507864,
],
], ],
], ],
]); ])->get();
``` ```
### Inserts, updates and deletes
Inserting, updating and deleting records works just like the original Eloquent. Please check [Laravel Docs' Eloquent section](https://laravel.com/docs/6.x/eloquent).
**Where** Here, only the MongoDB-specific operations are specified.
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where
### Inserts, updates and deletes ### MongoDB specific operations
Inserting, updating and deleting records works just like the original Eloquent. **Raw Expressions**
**Saving a new model** These expressions will be injected directly into the query.
```php ```php
$user = new User; User::whereRaw([
$user->name = 'John'; 'age' => ['$gt' => 30, '$lt' => 40],
$user->save(); ])->get();
``` ```
You may also use the create method to save a new model in a single line: 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.
**Cursor timeout**
To prevent `MongoCursorTimeout` exceptions, you can manually set a timeout value that will be applied to the cursor:
```php ```php
User::create(['name' => 'John']); DB::collection('users')->timeout(-1)->get();
``` ```
**Updating a model** **Upsert**
To update a model, you may retrieve it, change an attribute, and use the save method. Update or insert a document. Additional options for the update method are passed directly to the native update method.
```php ```php
$user = User::first(); // Query Builder
$user->email = 'john@foo.com'; DB::collection('users')
$user->save(); ->where('name', 'John')
->update($data, ['upsert' => true]);
// Eloquent
$user->update($data, ['upsert' => true]);
``` ```
*There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations* **Projections**
**Deleting a model** You can apply projections to your queries using the `project` method.
```php
DB::collection('items')
->project(['tags' => ['$slice' => 1]])
->get();
DB::collection('items')
->project(['tags' => ['$slice' => [3, 7]]])
->get();
```
To delete a model, simply call the delete method on the instance: **Projections with Pagination**
```php ```php
$user = User::first(); $limit = 25;
$user->delete(); $projections = ['id', 'name'];
DB::collection('items')
->paginate($limit, $projections);
``` ```
Or deleting a model by its key: **Push**
Add items to an array.
```php ```php
User::destroy('517c43667db388101e00000f'); DB::collection('users')
->where('name', 'John')
->push('items', 'boots');
$user->push('items', 'boots');
``` ```
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete ```php
DB::collection('users')
->where('name', 'John')
->push('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
### Dates $user->push('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
```
If you **DON'T** want duplicate items, set the third parameter to `true`:
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 ```php
DB::collection('users')
->where('name', 'John')
->push('items', 'boots', true);
Example: $user->push('items', 'boots', true);
```
**Pull**
Remove an item from an array.
```php ```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; DB::collection('users')
->where('name', 'John')
->pull('items', 'boots');
class User extends Eloquent { $user->pull('items', 'boots');
```
protected $dates = ['birthday']; ```php
DB::collection('users')
->where('name', 'John')
->pull('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
} $user->pull('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
``` ```
Which allows you to execute queries like: **Unset**
Remove one or more fields from a document.
```php ```php
$users = User::where('birthday', '>', new DateTime('-18 years'))->get(); DB::collection('users')
->where('name', 'John')
->unset('note');
$user->unset('note');
``` ```
### Relations Relationships
-------------
Supported relations are: ### Basic Usage
The only available relationships are:
- hasOne - hasOne
- hasMany - hasMany
- belongsTo - belongsTo
- belongsToMany - belongsToMany
The MongoDB-specific relationships are:
- embedsOne - embedsOne
- embedsMany - embedsMany
Example: Here is a small example:
```php ```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model;
class User extends Eloquent {
class User extends Model
{
public function items() public function items()
{ {
return $this->hasMany('Item'); return $this->hasMany(Item::class);
} }
} }
``` ```
And the inverse relation: The inverse relation of `hasMany` is `belongsTo`:
```php ```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model;
class Item extends Eloquent {
class Item extends Model
{
public function user() public function user()
{ {
return $this->belongsTo('User'); return $this->belongsTo(User::class);
} }
} }
``` ```
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`: ### belongsToMany and pivots
```php 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.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent { If you want to define custom keys for your relation, set it to `null`:
```php
use Jenssegers\Mongodb\Eloquent\Mode;
class User extends Model
{
public function groups() public function groups()
{ {
return $this->belongsToMany('Group', null, 'user_ids', 'group_ids'); return $this->belongsToMany(
Group::class, null, 'user_ids', 'group_ids'
);
} }
} }
``` ```
### EmbedsMany Relationship
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 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.
### 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. **REMEMBER**: These relations return Eloquent collections, they don't return query builder objects!
**REMEMBER**: these relations return Eloquent collections, they don't return query builder objects!
```php ```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model;
class User extends Eloquent {
class User extends Model
{
public function books() public function books()
{ {
return $this->embedsMany('Book'); return $this->embedsMany(Book::class);
} }
} }
``` ```
You can access the embedded models through the dynamic property: You can access the embedded models through the dynamic property:
```php ```php
$books = User::first()->books; $user = User::first();
foreach ($user->books as $book) {
//
}
``` ```
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
$book = Book::first();
$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(['title' => 'A Game of Thrones']); $book = $user->books()->save(
new Book(['title' => 'A Game of Thrones'])
$user = User::first(); );
$book = $user->books()->save($book);
// or // or
$book = $user->books()->create(['title' => 'A Game of Thrones']) $book =
$user->books()
->create(['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):
...@@ -821,69 +799,78 @@ You can update embedded models using their `save` method (available since releas ...@@ -821,69 +799,78 @@ You can update embedded models using their `save` method (available since releas
$book = $user->books()->first(); $book = $user->books()->first();
$book->title = 'A Game of Thrones'; $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->delete(); $book->delete();
// or
// Similar operation
$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'); use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model
{
public function books()
{
return $this->embedsMany(Book::class, 'local_key');
}
}
``` ```
Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections
### EmbedsOne Relations
### EmbedsOne Relationship
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\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model;
class Book extends Eloquent {
class Book extends Model
{
public function author() public function author()
{ {
return $this->embedsOne('Author'); return $this->embedsOne(Author::class);
} }
} }
``` ```
You can access the embedded models through the dynamic property: You can access the embedded models through the dynamic property:
```php ```php
$author = Book::first()->author; $book = Book::first();
$author = $book->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(['name' => 'John Doe']); $author = $book->author()->save(
new Author(['name' => 'John Doe'])
$book = Books::first(); );
$author = $book->author()->save($author); // Similar
// or $author =
$author = $book->author()->create(['name' => 'John Doe']); $book->author()
->create(['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):
...@@ -899,178 +886,231 @@ You can replace the embedded model with a new model like this: ...@@ -899,178 +886,231 @@ You can replace the embedded model with a new model like this:
```php ```php
$newAuthor = new Author(['name' => 'Jane Doe']); $newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor); $book->author()->save($newAuthor);
``` ```
### MySQL Relations Query Builder
-------------
### Basic Usage
The database driver plugs right into the original query builder.
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 use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations. 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.
Example SQL-based User model:
```php ```php
use Jenssegers\Mongodb\Eloquent\HybridRelations; $books = DB::collection('books')->get();
class User extends Eloquent { $hungerGames =
DB::collection('books')
->where('name', 'Hunger Games')
->first();
```
use HybridRelations; If you are familiar with [Eloquent Queries](http://laravel.com/docs/queries), there is the same functionality.
protected $connection = 'mysql'; ### Available operations
To see the available operations, check the [Eloquent](#eloquent) section.
public function messages() Schema
{ ------
return $this->hasMany('Message'); The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes.
}
} ### Basic Usage
```php
Schema::create('users', function ($collection) {
$collection->index('name');
$collection->unique('email');
});
``` ```
And the Mongodb-based Message model: You can also pass all the parameters specified [in the MongoDB docs](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types) to the `$options` parameter:
```php ```php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; Schema::create('users', function ($collection) {
$collection->index(
'username',
null,
null,
[
'sparse' => true,
'unique' => true,
'background' => true,
]
);
});
```
class Message extends Eloquent { Inherited operations:
- create and drop
- collection
- hasCollection
- index and dropIndex (compound indexes supported as well)
- unique
protected $connection = 'mongodb'; MongoDB specific operations:
- background
- sparse
- expire
- geospatial
public function user() All other (unsupported) operations are implemented as dummy pass-through methods because MongoDB does not use a predefined schema.
{
return $this->belongsTo('User');
}
} Read more about the schema builder on [Laravel Docs](https://laravel.com/docs/6.0/migrations#tables)
```
### Raw Expressions ### Geospatial indexes
These expressions will be injected directly into the query. Geospatial indexes are handy for querying location-based documents.
They come in two forms: `2d` and `2dsphere`. Use the schema builder to add these to a collection.
```php ```php
User::whereRaw(['age' => array('$gt' => 30, '$lt' => 40)])->get(); Schema::create('bars', function ($collection) {
$collection->geospatial('location', '2d');
});
``` ```
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. To add a `2dsphere` index:
```php ```php
// Returns a collection of User models. Schema::create('bars', function ($collection) {
$models = User::raw(function($collection) $collection->geospatial('location', '2dsphere');
{
return $collection->find();
});
// Returns the original MongoCursor.
$cursor = DB::collection('users')->raw(function($collection)
{
return $collection->find();
}); });
``` ```
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible: Extending
---------
```php ### Cross-Database Relationships
$model = User::raw()->findOne(['age' => array('$lt' => 18)]);
```
The internal MongoClient and MongoDB objects can be accessed like this: If you're using a hybrid MongoDB and SQL setup, you can define relationships across them.
```php The model will automatically return a MongoDB-related or SQL-related relation based on the type of the related model.
$client = DB::getMongoClient();
$db = DB::getMongoDB();
```
### MongoDB specific operations If you want this functionality to work both ways, your SQL-models will need to use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait.
**Cursor timeout** **This functionality only works for `hasOne`, `hasMany` and `belongsTo`.**
To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor: The MySQL model should use the `HybridRelations` trait:
```php ```php
DB::collection('users')->timeout(-1)->get(); use Jenssegers\Mongodb\Eloquent\HybridRelations;
```
**Upsert** class User extends Model
{
use HybridRelations;
Update or insert a document. Additional options for the update method are passed directly to the native update method. protected $connection = 'mysql';
```php public function messages()
DB::collection('users')->where('name', 'John') {
->update($data, ['upsert' => true]); return $this->hasMany(Message::class);
}
}
``` ```
Within your MongoDB model, you should define the relationship:
**Projections** ```php
use Jenssegers\Mongodb\Eloquent\Model;
You can apply projections to your queries using the `project` method. class Message extends Model
{
protected $connection = 'mongodb';
```php public function user()
DB::collection('items')->project(['tags' => ['$slice' => 1]])->get(); {
DB::collection('items')->project(['tags' => ['$slice' => [3, 7]]])->get(); return $this->belongsTo(User::class);
}
}
``` ```
**Projections with Pagination** ### Authentication
If you want to use Laravel's native Auth functionality, register this included service provider:
```php ```php
$limit = 25; Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class,
$projections = ['id', 'name'];
DB::collection('items')->paginate($limit, $projections);
``` ```
This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders.
**Push** If you don't use password reminders, you don't have to register this service provider and everything else should work just fine.
Add items to an array. ### Queues
If you want to use MongoDB as your database backend, change the driver in `config/queue.php`:
```php ```php
DB::collection('users')->where('name', 'John')->push('items', 'boots'); 'connections' => [
DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']); 'database' => [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
],
``` ```
If you don't want duplicate items, set the third parameter to `true`: If you want to use MongoDB to handle failed jobs, change the database in `config/queue.php`:
```php ```php
DB::collection('users')->where('name', 'John')->push('items', 'boots', true); 'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mongodb'),
'table' => 'failed_jobs',
],
``` ```
**Pull** Or simply set your own `QUEUE_FAILED_DRIVER` environment variable to `mongodb`
```env
QUEUE_FAILED_DRIVER=mongodb
```
Remove an item from an array. Last, add the service provider in `config/app.php`:
```php ```php
DB::collection('users')->where('name', 'John')->pull('items', 'boots'); Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
``` ```
**Unset** Upgrading
---------
Remove one or more fields from a document. #### Upgrading from version 2 to 3
```php In this new major release which supports the new MongoDB PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait.
DB::collection('users')->where('name', 'John')->unset('note');
```
You can also perform an unset on a model. Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files or your registered alias.
```php ```php
$user = User::where('name', 'John')->first(); use Jenssegers\Mongodb\Eloquent\Model;
$user->unset('note');
class User extends Model
{
//
}
``` ```
### Query Caching If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`.
You may easily cache the results of a query using the remember method: Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package.
```php ```php
$users = User::remember(10)->get(); use Jenssegers\Mongodb\Eloquent\HybridRelations;
```
class User extends Model
{
*From: http://laravel.com/docs/queries#caching-queries* use HybridRelations;
### Query Logging protected $connection = 'mysql';
}
```
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: Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations.
```php ```php
DB::connection()->disableQueryLog(); $books = $user->books()->sortBy('title')->get();
``` ```
*From: http://laravel.com/docs/database#query-logging*
...@@ -23,14 +23,15 @@ ...@@ -23,14 +23,15 @@
"illuminate/container": "^5.8|^6.0", "illuminate/container": "^5.8|^6.0",
"illuminate/database": "^5.8|^6.0", "illuminate/database": "^5.8|^6.0",
"illuminate/events": "^5.8|^6.0", "illuminate/events": "^5.8|^6.0",
"mongodb/mongodb": "^1.4" "mongodb/mongodb": "^1.4",
"cedx/coveralls": "^11.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.0|^7.0|^8.0", "phpunit/phpunit": "^6.0|^7.0|^8.0",
"orchestra/testbench": "^3.1|^4.0", "orchestra/testbench": "^3.1|^4.0",
"mockery/mockery": "^1.0", "mockery/mockery": "^1.0",
"satooshi/php-coveralls": "^2.0", "doctrine/dbal": "^2.5",
"doctrine/dbal": "^2.5" "phpunit/phpcov": "^6.0"
}, },
"autoload": { "autoload": {
"psr-0": { "psr-0": {
......
...@@ -40,11 +40,17 @@ ...@@ -40,11 +40,17 @@
<file>tests/ValidationTest.php</file> <file>tests/ValidationTest.php</file>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<php> <php>
<env name="MONGO_HOST" value="mongodb"/> <env name="MONGO_HOST" value="mongodb"/>
<env name="MONGO_DATABASE" value="unittest"/> <env name="MONGO_DATABASE" value="unittest"/>
<env name="MONGO_PORT" value="27017"/> <env name="MONGO_PORT" value="27017"/>
<env name="MYSQL_HOST" value="mysql"/> <env name="MYSQL_HOST" value="mysql"/>
<env name="MYSQL_PORT" value="3306"/>
<env name="MYSQL_DATABASE" value="unittest"/> <env name="MYSQL_DATABASE" value="unittest"/>
<env name="MYSQL_USERNAME" value="root"/> <env name="MYSQL_USERNAME" value="root"/>
<env name="QUEUE_CONNECTION" value="database"/> <env name="QUEUE_CONNECTION" value="database"/>
......
...@@ -25,6 +25,23 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -25,6 +25,23 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
* @inheritdoc * @inheritdoc
*/ */
protected function tokenExpired($createdAt) protected function tokenExpired($createdAt)
{
$createdAt = $this->convertDateTime($createdAt);
return parent::tokenExpired($createdAt);
}
/**
* @inheritdoc
*/
protected function tokenRecentlyCreated($createdAt)
{
$createdAt = $this->convertDateTime($createdAt);
return parent::tokenRecentlyCreated($createdAt);
}
private function convertDateTime($createdAt)
{ {
// Convert UTCDateTime to a date string. // Convert UTCDateTime to a date string.
if ($createdAt instanceof UTCDateTime) { if ($createdAt instanceof UTCDateTime) {
...@@ -37,6 +54,6 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -37,6 +54,6 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
$createdAt = $date->format('Y-m-d H:i:s'); $createdAt = $date->format('Y-m-d H:i:s');
} }
return parent::tokenExpired($createdAt); return $createdAt;
} }
} }
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
namespace Jenssegers\Mongodb\Eloquent; namespace Jenssegers\Mongodb\Eloquent;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Helpers\EloquentBuilder; use Jenssegers\Mongodb\Helpers\EloquentBuilder;
...@@ -11,6 +10,7 @@ use Jenssegers\Mongodb\Relations\BelongsToMany; ...@@ -11,6 +10,7 @@ use Jenssegers\Mongodb\Relations\BelongsToMany;
use Jenssegers\Mongodb\Relations\HasMany; use Jenssegers\Mongodb\Relations\HasMany;
use Jenssegers\Mongodb\Relations\HasOne; use Jenssegers\Mongodb\Relations\HasOne;
use Jenssegers\Mongodb\Relations\MorphTo; use Jenssegers\Mongodb\Relations\MorphTo;
use Jenssegers\Mongodb\Relations\MorphMany;
trait HybridRelations trait HybridRelations
{ {
...@@ -184,7 +184,7 @@ trait HybridRelations ...@@ -184,7 +184,7 @@ trait HybridRelations
// there are multiple types in the morph and we can't use single queries. // there are multiple types in the morph and we can't use single queries.
if (($class = $this->$type) === null) { if (($class = $this->$type) === null) {
return new MorphTo( return new MorphTo(
$this->newQuery(), $this, $id, null, $type, $name $this->newQuery(), $this, $id, $ownerKey, $type, $name
); );
} }
...@@ -195,8 +195,10 @@ trait HybridRelations ...@@ -195,8 +195,10 @@ trait HybridRelations
$instance = new $class; $instance = new $class;
$ownerKey = $ownerKey ?? $instance->getKeyName();
return new MorphTo( return new MorphTo(
$instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name $instance->newQuery(), $this, $id, $ownerKey, $type, $name
); );
} }
......
...@@ -118,7 +118,7 @@ abstract class Model extends BaseModel ...@@ -118,7 +118,7 @@ abstract class Model extends BaseModel
*/ */
public function freshTimestamp() public function freshTimestamp()
{ {
return new UTCDateTime(time() * 1000); return new UTCDateTime(Carbon::now());
} }
/** /**
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb; namespace Jenssegers\Mongodb;
use DB;
use Illuminate\Queue\QueueServiceProvider; use Illuminate\Queue\QueueServiceProvider;
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider; use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
...@@ -13,7 +14,7 @@ class MongodbQueueServiceProvider extends QueueServiceProvider ...@@ -13,7 +14,7 @@ class MongodbQueueServiceProvider extends QueueServiceProvider
protected function registerFailedJobServices() protected function registerFailedJobServices()
{ {
// Add compatible queue failer if mongodb is configured. // Add compatible queue failer if mongodb is configured.
if (config('queue.failed.database') == 'mongodb') { if (DB::connection(config('queue.failed.database'))->getDriverName() == 'mongodb') {
$this->app->singleton('queue.failer', function ($app) { $this->app->singleton('queue.failer', function ($app) {
return new MongoFailedJobProvider($app['db'], config('queue.failed.database'), config('queue.failed.table')); return new MongoFailedJobProvider($app['db'], config('queue.failed.database'), config('queue.failed.table'));
}); });
......
...@@ -232,7 +232,7 @@ class Builder extends BaseBuilder ...@@ -232,7 +232,7 @@ class Builder extends BaseBuilder
$wheres = $this->compileWheres(); $wheres = $this->compileWheres();
// Use MongoDB's aggregation framework when using grouping or aggregation functions. // Use MongoDB's aggregation framework when using grouping or aggregation functions.
if ($this->groups || $this->aggregate || $this->paginating) { if ($this->groups || $this->aggregate) {
$group = []; $group = [];
$unwinds = []; $unwinds = [];
...@@ -267,24 +267,34 @@ class Builder extends BaseBuilder ...@@ -267,24 +267,34 @@ class Builder extends BaseBuilder
$column = implode('.', $splitColumns); $column = implode('.', $splitColumns);
} }
// Null coalense only > 7.2
$aggregations = blank($this->aggregate['columns']) ? [] : $this->aggregate['columns'];
if (in_array('*', $aggregations) && $function == 'count') {
// When ORM is paginating, count doesnt need a aggregation, just a cursor operation
// elseif added to use this only in pagination
// https://docs.mongodb.com/manual/reference/method/cursor.count/
// count method returns int
$totalResults = $this->collection->count($wheres);
// Preserving format expected by framework
$results = [
[
'_id' => null,
'aggregate' => $totalResults
]
];
return $this->useCollections ? new Collection($results) : $results;
} elseif ($function == 'count') {
// Translate count into sum. // Translate count into sum.
if ($function == 'count') {
$group['aggregate'] = ['$sum' => 1]; $group['aggregate'] = ['$sum' => 1];
} // Pass other functions directly. } else {
else {
$group['aggregate'] = ['$' . $function => '$' . $column]; $group['aggregate'] = ['$' . $function => '$' . $column];
} }
} }
} }
// When using pagination, we limit the number of returned columns
// by adding a projection.
if ($this->paginating) {
foreach ($this->columns as $column) {
$this->projections[$column] = 1;
}
}
// The _id field is mandatory when using grouping. // The _id field is mandatory when using grouping.
if ($group && empty($group['_id'])) { if ($group && empty($group['_id'])) {
$group['_id'] = null; $group['_id'] = null;
......
...@@ -46,6 +46,10 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -46,6 +46,10 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
{ {
$job = $this->getTable()->find($id); $job = $this->getTable()->find($id);
if (!$job) {
return;
}
$job['id'] = (string) $job['_id']; $job['id'] = (string) $job['_id'];
return (object) $job; return (object) $job;
......
...@@ -64,7 +64,7 @@ class MongoQueue extends DatabaseQueue ...@@ -64,7 +64,7 @@ class MongoQueue extends DatabaseQueue
$job = $this->database->getCollection($this->table)->findOneAndUpdate( $job = $this->database->getCollection($this->table)->findOneAndUpdate(
[ [
'queue' => $this->getQueue($queue), 'queue' => $this->getQueue($queue),
'reserved' => 0, 'reserved' => ['$ne' => 1],
'available_at' => ['$lte' => Carbon::now()->getTimestamp()], 'available_at' => ['$lte' => Carbon::now()->getTimestamp()],
], ],
[ [
...@@ -72,6 +72,9 @@ class MongoQueue extends DatabaseQueue ...@@ -72,6 +72,9 @@ class MongoQueue extends DatabaseQueue
'reserved' => 1, 'reserved' => 1,
'reserved_at' => Carbon::now()->getTimestamp(), 'reserved_at' => Carbon::now()->getTimestamp(),
], ],
'$inc' => [
'attempts' => 1,
],
], ],
[ [
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
...@@ -94,24 +97,15 @@ class MongoQueue extends DatabaseQueue ...@@ -94,24 +97,15 @@ class MongoQueue extends DatabaseQueue
protected function releaseJobsThatHaveBeenReservedTooLong($queue) protected function releaseJobsThatHaveBeenReservedTooLong($queue)
{ {
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp(); $expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$now = time();
$reserved = $this->database->collection($this->table) $reserved = $this->database->collection($this->table)
->where('queue', $this->getQueue($queue)) ->where('queue', $this->getQueue($queue))
->where(function ($query) use ($expiration, $now) { ->whereNotNull('reserved_at')
// Check for available jobs ->where('reserved_at', '<=', $expiration)
$query->where(function ($query) use ($now) { ->get();
$query->whereNull('reserved_at');
$query->where('available_at', '<=', $now);
});
// Check for jobs that are reserved but have expired
$query->orWhere('reserved_at', '<=', $expiration);
})->get();
foreach ($reserved as $job) { foreach ($reserved as $job) {
$attempts = $job['attempts'] + 1; $this->releaseJob($job['_id'], $job['attempts']);
$this->releaseJob($job['_id'], $attempts);
} }
} }
......
<?php
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\MorphMany as EloquentMorphMany;
class MorphMany extends EloquentMorphMany
{
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
*
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
{
return 'whereIn';
}
}
...@@ -74,6 +74,54 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -74,6 +74,54 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
* @inheritdoc * @inheritdoc
*/ */
public function dropIndex($indexOrColumns = null) public function dropIndex($indexOrColumns = null)
{
$indexOrColumns = $this->transformColumns($indexOrColumns);
$this->collection->dropIndex($indexOrColumns);
return $this;
}
/**
* Indicate that the given index should be dropped, but do not fail if it didn't exist.
*
* @param string|array $indexOrColumns
* @return Blueprint
*/
public function dropIndexIfExists($indexOrColumns = null)
{
if ($this->hasIndex($indexOrColumns)) {
$this->dropIndex($indexOrColumns);
}
return $this;
}
/**
* Check whether the given index exists.
*
* @param string|array $indexOrColumns
* @return bool
*/
public function hasIndex($indexOrColumns = null)
{
$indexOrColumns = $this->transformColumns($indexOrColumns);
foreach ($this->collection->listIndexes() as $index) {
if (is_array($indexOrColumns) && in_array($index->getName(), $indexOrColumns)) {
return true;
}
if (is_string($indexOrColumns) && $index->getName() == $indexOrColumns) {
return true;
}
}
return false;
}
/**
* @param string|array $indexOrColumns
* @return string
*/
protected function transformColumns($indexOrColumns)
{ {
if (is_array($indexOrColumns)) { if (is_array($indexOrColumns)) {
$indexOrColumns = $this->fluent($indexOrColumns); $indexOrColumns = $this->fluent($indexOrColumns);
...@@ -85,12 +133,9 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -85,12 +133,9 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
$transform[$column] = $column . '_1'; $transform[$column] = $column . '_1';
} }
$indexOrColumns = join('_', $transform); $indexOrColumns = implode('_', $transform);
} }
return $indexOrColumns;
$this->collection->dropIndex($indexOrColumns);
return $this;
} }
/** /**
......
...@@ -28,6 +28,7 @@ class AuthTest extends TestCase ...@@ -28,6 +28,7 @@ class AuthTest extends TestCase
public function testRemindOld() public function testRemindOld()
{ {
if (Application::VERSION >= '5.2') { if (Application::VERSION >= '5.2') {
$this->expectNotToPerformAssertions();
return; return;
} }
......
...@@ -434,6 +434,16 @@ class ModelTest extends TestCase ...@@ -434,6 +434,16 @@ class ModelTest extends TestCase
$this->assertEquals((string) $user->getAttribute('entry.date')->format('Y-m-d H:i:s'), $data['entry']['date']); $this->assertEquals((string) $user->getAttribute('entry.date')->format('Y-m-d H:i:s'), $data['entry']['date']);
} }
public function testCarbonDateMockingWorks()
{
$fakeDate = \Carbon\Carbon::createFromDate(2000, 01, 01);
Carbon::setTestNow($fakeDate);
$item = Item::create(['name' => 'sword']);
$this->assertLessThan(1, $fakeDate->diffInSeconds($item->created_at));
}
public function testIdAttribute(): void public function testIdAttribute(): void
{ {
/** @var User $user */ /** @var User $user */
......
<?php <?php
declare(strict_types=1); declare(strict_types=1);
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
class QueueTest extends TestCase class QueueTest extends TestCase
{ {
public function setUp(): void public function setUp(): void
...@@ -55,4 +57,38 @@ class QueueTest extends TestCase ...@@ -55,4 +57,38 @@ class QueueTest extends TestCase
$job->delete(); $job->delete();
$this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count()); $this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count());
} }
public function testFailQueueJob(): void
{
$provider = app('queue.failer');
$this->assertInstanceOf(MongoFailedJobProvider::class, $provider);
}
public function testFindFailJobNull(): void
{
Config::set('queue.failed.database', 'mongodb');
$provider = app('queue.failer');
$this->assertNull($provider->find(1));
}
public function testIncrementAttempts(): void
{
$job_id = Queue::push('test1', ['action' => 'QueueJobExpired'], 'test');
$this->assertNotNull($job_id);
$job_id = Queue::push('test2', ['action' => 'QueueJobExpired'], 'test');
$this->assertNotNull($job_id);
$job = Queue::pop('test');
$this->assertEquals(1, $job->attempts());
$job->delete();
$others_jobs = Queue::getDatabase()
->table(Config::get('queue.connections.database.table'))
->get();
$this->assertCount(1, $others_jobs);
$this->assertEquals(0, $others_jobs[0]['attempts']);
}
} }
...@@ -147,6 +147,76 @@ class SchemaTest extends TestCase ...@@ -147,6 +147,76 @@ class SchemaTest extends TestCase
$this->assertFalse($index); $this->assertFalse($index);
} }
public function testDropIndexIfExists(): void
{
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->unique('uniquekey');
$collection->dropIndexIfExists('uniquekey_1');
});
$index = $this->getIndex('newcollection', 'uniquekey');
$this->assertEquals(null, $index);
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->unique('uniquekey');
$collection->dropIndexIfExists(['uniquekey']);
});
$index = $this->getIndex('newcollection', 'uniquekey');
$this->assertEquals(null, $index);
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->index(['field_a', 'field_b']);
});
$index = $this->getIndex('newcollection', 'field_a_1_field_b_1');
$this->assertNotNull($index);
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->dropIndexIfExists(['field_a', 'field_b']);
});
$index = $this->getIndex('newcollection', 'field_a_1_field_b_1');
$this->assertFalse($index);
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->index(['field_a', 'field_b'], 'custom_index_name');
});
$index = $this->getIndex('newcollection', 'custom_index_name');
$this->assertNotNull($index);
Schema::collection('newcollection', function (Blueprint $collection) {
$collection->dropIndexIfExists('custom_index_name');
});
$index = $this->getIndex('newcollection', 'custom_index_name');
$this->assertFalse($index);
}
public function testHasIndex(): void
{
$instance = $this;
Schema::collection('newcollection', function (Blueprint $collection) use ($instance) {
$collection->index('myhaskey1');
$instance->assertTrue($collection->hasIndex('myhaskey1_1'));
$instance->assertFalse($collection->hasIndex('myhaskey1'));
});
Schema::collection('newcollection', function (Blueprint $collection) use ($instance) {
$collection->index('myhaskey2');
$instance->assertTrue($collection->hasIndex(['myhaskey2']));
$instance->assertFalse($collection->hasIndex(['myhaskey2_1']));
});
Schema::collection('newcollection', function (Blueprint $collection) use ($instance) {
$collection->index(['field_a', 'field_b']);
$instance->assertTrue($collection->hasIndex(['field_a_1_field_b']));
$instance->assertFalse($collection->hasIndex(['field_a_1_field_b_1']));
});
}
public function testBackground(): void public function testBackground(): void
{ {
Schema::collection('newcollection', function ($collection) { Schema::collection('newcollection', function ($collection) {
...@@ -230,6 +300,7 @@ class SchemaTest extends TestCase ...@@ -230,6 +300,7 @@ class SchemaTest extends TestCase
$collection->boolean('activated')->default(0); $collection->boolean('activated')->default(0);
$collection->integer('user_id')->unsigned(); $collection->integer('user_id')->unsigned();
}); });
$this->expectNotToPerformAssertions();
} }
public function testSparseUnique(): void public function testSparseUnique(): void
......
...@@ -28,6 +28,7 @@ class TestCase extends Orchestra\Testbench\TestCase ...@@ -28,6 +28,7 @@ class TestCase extends Orchestra\Testbench\TestCase
{ {
return [ return [
Jenssegers\Mongodb\MongodbServiceProvider::class, Jenssegers\Mongodb\MongodbServiceProvider::class,
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class, Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class,
Jenssegers\Mongodb\Validation\ValidationServiceProvider::class, Jenssegers\Mongodb\Validation\ValidationServiceProvider::class,
]; ];
...@@ -50,6 +51,7 @@ class TestCase extends Orchestra\Testbench\TestCase ...@@ -50,6 +51,7 @@ class TestCase extends Orchestra\Testbench\TestCase
$app['config']->set('database.default', 'mongodb'); $app['config']->set('database.default', 'mongodb');
$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']);
$app['config']->set('database.connections.mongodb2', $config['connections']['mongodb']);
$app['config']->set('database.connections.dsn_mongodb', $config['connections']['dsn_mongodb']); $app['config']->set('database.connections.dsn_mongodb', $config['connections']['dsn_mongodb']);
$app['config']->set('auth.model', 'User'); $app['config']->set('auth.model', 'User');
...@@ -63,5 +65,6 @@ class TestCase extends Orchestra\Testbench\TestCase ...@@ -63,5 +65,6 @@ class TestCase extends Orchestra\Testbench\TestCase
'queue' => 'default', 'queue' => 'default',
'expire' => 60, 'expire' => 60,
]); ]);
$app['config']->set('queue.failed.database', 'mongodb2');
} }
} }
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
$mongoHost = env('MONGO_HOST', 'mongodb'); $mongoHost = env('MONGO_HOST', 'mongodb');
$mongoPort = env('MONGO_PORT') ? (int) env('MONGO_PORT') : 27017; $mongoPort = env('MONGO_PORT') ? (int) env('MONGO_PORT') : 27017;
$mysqlPort = env('MYSQL_PORT') ? (int) env('MYSQL_PORT') : 3306;
return [ return [
...@@ -23,6 +24,7 @@ return [ ...@@ -23,6 +24,7 @@ return [
'mysql' => [ 'mysql' => [
'driver' => 'mysql', 'driver' => 'mysql',
'host' => env('MYSQL_HOST', 'mysql'), 'host' => env('MYSQL_HOST', 'mysql'),
'port' => $mysqlPort,
'database' => env('MYSQL_DATABASE', 'unittest'), 'database' => env('MYSQL_DATABASE', 'unittest'),
'username' => env('MYSQL_USERNAME', 'root'), 'username' => env('MYSQL_USERNAME', 'root'),
'password' => env('MYSQL_PASSWORD', ''), 'password' => env('MYSQL_PASSWORD', ''),
......
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