Unverified Commit 0ae6a63d authored by Rémi Collin's avatar Rémi Collin Committed by GitHub

Merge pull request #1 from jenssegers/master

Merge back master
parents c0cae3e1 1bb259ae
language: php language: php
php: php:
- 5.6
- 7 - 7
- 7.1 - 7.1
......
...@@ -41,6 +41,7 @@ composer require jenssegers/mongodb ...@@ -41,6 +41,7 @@ composer require jenssegers/mongodb
5.2.x | 2.3.x or 3.0.x 5.2.x | 2.3.x or 3.0.x
5.3.x | 3.1.x or 3.2.x 5.3.x | 3.1.x or 3.2.x
5.4.x | 3.2.x 5.4.x | 3.2.x
5.5.x | 3.3.x
And add the service provider in `config/app.php`: And add the service provider in `config/app.php`:
...@@ -102,6 +103,15 @@ Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rathe ...@@ -102,6 +103,15 @@ Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rathe
$books = $user->books()->sortBy('title'); $books = $user->books()->sortBy('title');
``` ```
Testing
-------
To run the test for this package, run:
```
docker-compose up
```
Configuration Configuration
------------- -------------
...@@ -143,6 +153,18 @@ You can connect to multiple servers or replica sets with the following configura ...@@ -143,6 +153,18 @@ You can connect to multiple servers or replica sets with the following configura
], ],
``` ```
Alternatively, you can use MongoDB connection string:
```php
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('DB_DSN'),
'database' => env('DB_DATABASE'),
],
```
Please refer to MongoDB official docs for its URI format: https://docs.mongodb.com/manual/reference/connection-string/
Eloquent Eloquent
-------- --------
...@@ -942,7 +964,7 @@ $cursor = DB::collection('users')->raw(function($collection) ...@@ -942,7 +964,7 @@ $cursor = DB::collection('users')->raw(function($collection)
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(['age' => array('$lt' => 18])); $model = User::raw()->findOne(['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:
......
...@@ -11,17 +11,18 @@ ...@@ -11,17 +11,18 @@
], ],
"license" : "MIT", "license" : "MIT",
"require": { "require": {
"illuminate/support": "^5.1", "illuminate/support": "^5.5",
"illuminate/container": "^5.1", "illuminate/container": "^5.5",
"illuminate/database": "^5.1", "illuminate/database": "^5.5",
"illuminate/events": "^5.1", "illuminate/events": "^5.5",
"mongodb/mongodb": "^1.0.0" "mongodb/mongodb": "^1.0.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^5.0|^6.0", "phpunit/phpunit": "^6.0",
"orchestra/testbench": "^3.1", "orchestra/testbench": "^3.1",
"mockery/mockery": "^0.9", "mockery/mockery": "^1.0",
"satooshi/php-coveralls": "^1.0" "satooshi/php-coveralls": "^2.0",
"doctrine/dbal": "^2.5"
}, },
"autoload": { "autoload": {
"psr-0": { "psr-0": {
......
version: '3'
services:
php:
build:
context: .
dockerfile: docker/Dockerfile
volumes:
- .:/code
working_dir: /code
command: docker/entrypoint.sh
depends_on:
- mysql
- mongodb
mysql:
image: mysql
environment:
MYSQL_ROOT_PASSWORD:
MYSQL_DATABASE: unittest
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
logging:
driver: none
mongodb:
image: mongo
logging:
driver: none
FROM php:7.1-cli
RUN apt-get update && \
apt-get install -y autoconf pkg-config libssl-dev && \
pecl install mongodb && docker-php-ext-enable mongodb && \
docker-php-ext-install -j$(nproc) pdo pdo_mysql
#!/usr/bin/env bash
sleep 3 && php ./vendor/bin/phpunit
...@@ -27,7 +27,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -27,7 +27,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
$date = $token['created_at']->toDateTime(); $date = $token['created_at']->toDateTime();
$date->setTimezone(new DateTimeZone(date_default_timezone_get())); $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$token['created_at'] = $date->format('Y-m-d H:i:s'); $token['created_at'] = $date->format('Y-m-d H:i:s');
} elseif (is_array($token['created_at']) and isset($token['created_at']['date'])) { } elseif (is_array($token['created_at']) && isset($token['created_at']['date'])) {
$date = new DateTime($token['created_at']['date'], new DateTimeZone(isset($token['created_at']['timezone']) ? $token['created_at']['timezone'] : 'UTC')); $date = new DateTime($token['created_at']['date'], new DateTimeZone(isset($token['created_at']['timezone']) ? $token['created_at']['timezone'] : 'UTC'));
$date->setTimezone(new DateTimeZone(date_default_timezone_get())); $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$token['created_at'] = $date->format('Y-m-d H:i:s'); $token['created_at'] = $date->format('Y-m-d H:i:s');
......
...@@ -8,7 +8,7 @@ use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; ...@@ -8,7 +8,7 @@ use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Foundation\Auth\Access\Authorizable;
use Jenssegers\Mongodb\Eloquent\Model as Model; use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model implements class User extends Model implements
AuthenticatableContract, AuthenticatableContract,
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
namespace Jenssegers\Mongodb; namespace Jenssegers\Mongodb;
use Illuminate\Database\Connection as BaseConnection; use Illuminate\Database\Connection as BaseConnection;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use MongoDB\Client; use MongoDB\Client;
class Connection extends BaseConnection class Connection extends BaseConnection
...@@ -34,7 +36,7 @@ class Connection extends BaseConnection ...@@ -34,7 +36,7 @@ class Connection extends BaseConnection
$dsn = $this->getDsn($config); $dsn = $this->getDsn($config);
// You can pass options directly to the MongoDB constructor // You can pass options directly to the MongoDB constructor
$options = array_get($config, 'options', []); $options = Arr::get($config, 'options', []);
// Create the connection // Create the connection
$this->connection = $this->createConnection($dsn, $config, $options); $this->connection = $this->createConnection($dsn, $config, $options);
...@@ -149,18 +151,43 @@ class Connection extends BaseConnection ...@@ -149,18 +151,43 @@ class Connection extends BaseConnection
} }
/** /**
* Create a DSN string from a configuration. * Determine if the given configuration array has a UNIX socket value.
*
* @param array $config
* @return bool
*/
protected function hasDsnString(array $config)
{
return isset($config['dsn']) && ! empty($config['dsn']);
}
/**
* Get the DSN string for a socket configuration.
* *
* @param array $config * @param array $config
* @return string * @return string
*/ */
protected function getDsn(array $config) protected function getDsnString(array $config)
{ {
// Check if the user passed a complete dsn to the configuration. $dsn_string = $config['dsn'];
if (!empty($config['dsn'])) {
return $config['dsn']; if (Str::contains($dsn_string, 'mongodb://')) {
$dsn_string = Str::replaceFirst('mongodb://', '', $dsn_string);
} }
$dsn_string = rawurlencode($dsn_string);
return "mongodb://{$dsn_string}";
}
/**
* Get the DSN string for a host / port configuration.
*
* @param array $config
* @return string
*/
protected function getHostDsn(array $config)
{
// Treat host option as array of hosts // Treat host option as array of hosts
$hosts = is_array($config['host']) ? $config['host'] : [$config['host']]; $hosts = is_array($config['host']) ? $config['host'] : [$config['host']];
...@@ -177,6 +204,19 @@ class Connection extends BaseConnection ...@@ -177,6 +204,19 @@ class Connection extends BaseConnection
return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : ''); return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
} }
/**
* Create a DSN string from a configuration.
*
* @param array $config
* @return string
*/
protected function getDsn(array $config)
{
return $this->hasDsnString($config)
? $this->getDsnString($config)
: $this->getHostDsn($config);
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
......
...@@ -143,6 +143,14 @@ class Builder extends EloquentBuilder ...@@ -143,6 +143,14 @@ class Builder extends EloquentBuilder
return parent::decrement($column, $amount, $extra); return parent::decrement($column, $amount, $extra);
} }
/**
* @inheritdoc
*/
public function chunkById($count, callable $callback, $column = '_id', $alias = null)
{
return parent::chunkById($count, $callback, $column, $alias);
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -162,10 +170,18 @@ class Builder extends EloquentBuilder ...@@ -162,10 +170,18 @@ class Builder extends EloquentBuilder
return $this->model->newFromBuilder((array) $results); return $this->model->newFromBuilder((array) $results);
} // The result is a single object. } // The result is a single object.
elseif (is_array($results) and array_key_exists('_id', $results)) { elseif (is_array($results) && array_key_exists('_id', $results)) {
return $this->model->newFromBuilder((array) $results); return $this->model->newFromBuilder((array) $results);
} }
return $results; return $results;
} }
/**
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->query->getConnection();
}
} }
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb\Eloquent; namespace Jenssegers\Mongodb\Eloquent;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Relations\EmbedsMany; use Jenssegers\Mongodb\Relations\EmbedsMany;
use Jenssegers\Mongodb\Relations\EmbedsOne; use Jenssegers\Mongodb\Relations\EmbedsOne;
...@@ -32,7 +33,7 @@ trait EmbedsRelations ...@@ -32,7 +33,7 @@ trait EmbedsRelations
} }
if (is_null($foreignKey)) { if (is_null($foreignKey)) {
$foreignKey = snake_case(class_basename($this)); $foreignKey = Str::snake(class_basename($this));
} }
$query = $this->newQuery(); $query = $this->newQuery();
...@@ -67,7 +68,7 @@ trait EmbedsRelations ...@@ -67,7 +68,7 @@ trait EmbedsRelations
} }
if (is_null($foreignKey)) { if (is_null($foreignKey)) {
$foreignKey = snake_case(class_basename($this)); $foreignKey = Str::snake(class_basename($this));
} }
$query = $this->newQuery(); $query = $this->newQuery();
......
...@@ -214,11 +214,20 @@ trait HybridRelations ...@@ -214,11 +214,20 @@ trait HybridRelations
* @param string $collection * @param string $collection
* @param string $foreignKey * @param string $foreignKey
* @param string $otherKey * @param string $otherKey
* @param string $parentKey
* @param string $relatedKey
* @param string $relation * @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/ */
public function belongsToMany($related, $collection = null, $foreignKey = null, $otherKey = null, $relation = null) public function belongsToMany(
{ $related,
$collection = null,
$foreignKey = null,
$otherKey = null,
$parentKey = null,
$relatedKey = null,
$relation = null
) {
// If no relationship name was passed, we will pull backtraces to get the // If no relationship name was passed, we will pull backtraces to get the
// name of the calling function. We will use that function name as the // name of the calling function. We will use that function name as the
// title of this relation since that is a great convention to apply. // title of this relation since that is a great convention to apply.
...@@ -228,7 +237,15 @@ trait HybridRelations ...@@ -228,7 +237,15 @@ trait HybridRelations
// Check if it is a relation with an original model. // Check if it is a relation with an original model.
if (!is_subclass_of($related, \Jenssegers\Mongodb\Eloquent\Model::class)) { if (!is_subclass_of($related, \Jenssegers\Mongodb\Eloquent\Model::class)) {
return parent::belongsToMany($related, $collection, $foreignKey, $otherKey, $relation); return parent::belongsToMany(
$related,
$collection,
$foreignKey,
$otherKey,
$parentKey,
$relatedKey,
$relation
);
} }
// First, we'll need to determine the foreign key and "other key" for the // First, we'll need to determine the foreign key and "other key" for the
...@@ -252,7 +269,16 @@ trait HybridRelations ...@@ -252,7 +269,16 @@ trait HybridRelations
// appropriate query constraint and entirely manages the hydrations. // appropriate query constraint and entirely manages the hydrations.
$query = $instance->newQuery(); $query = $instance->newQuery();
return new BelongsToMany($query, $this, $collection, $foreignKey, $otherKey, $relation); return new BelongsToMany(
$query,
$this,
$collection,
$foreignKey,
$otherKey,
$parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(),
$relation
);
} }
/** /**
...@@ -274,6 +300,10 @@ trait HybridRelations ...@@ -274,6 +300,10 @@ trait HybridRelations
*/ */
public function newEloquentBuilder($query) public function newEloquentBuilder($query)
{ {
if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) {
return new Builder($query);
} else {
return new EloquentBuilder($query); return new EloquentBuilder($query);
} }
}
} }
...@@ -6,6 +6,7 @@ use Carbon\Carbon; ...@@ -6,6 +6,7 @@ use Carbon\Carbon;
use DateTime; use DateTime;
use Illuminate\Database\Eloquent\Model as BaseModel; use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder; use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
...@@ -46,7 +47,7 @@ abstract class Model extends BaseModel ...@@ -46,7 +47,7 @@ abstract class Model extends BaseModel
{ {
// If we don't have a value for 'id', we will use the Mongo '_id' value. // If we don't have a value for 'id', we will use the Mongo '_id' value.
// This allows us to work with models in a more sql-like way. // This allows us to work with models in a more sql-like way.
if (!$value and array_key_exists('_id', $this->attributes)) { if (!$value && array_key_exists('_id', $this->attributes)) {
$value = $this->attributes['_id']; $value = $this->attributes['_id'];
} }
...@@ -131,12 +132,12 @@ abstract class Model extends BaseModel ...@@ -131,12 +132,12 @@ abstract class Model extends BaseModel
} }
// Dot notation support. // Dot notation support.
if (str_contains($key, '.') and array_has($this->attributes, $key)) { if (Str::contains($key, '.') && Arr::has($this->attributes, $key)) {
return $this->getAttributeValue($key); return $this->getAttributeValue($key);
} }
// This checks for embedded relation support. // This checks for embedded relation support.
if (method_exists($this, $key) and !method_exists(self::class, $key)) { if (method_exists($this, $key) && !method_exists(self::class, $key)) {
return $this->getRelationValue($key); return $this->getRelationValue($key);
} }
...@@ -149,8 +150,8 @@ abstract class Model extends BaseModel ...@@ -149,8 +150,8 @@ abstract class Model extends BaseModel
protected function getAttributeFromArray($key) protected function getAttributeFromArray($key)
{ {
// Support keys in dot notation. // Support keys in dot notation.
if (str_contains($key, '.')) { if (Str::contains($key, '.')) {
return array_get($this->attributes, $key); return Arr::get($this->attributes, $key);
} }
return parent::getAttributeFromArray($key); return parent::getAttributeFromArray($key);
...@@ -162,17 +163,17 @@ abstract class Model extends BaseModel ...@@ -162,17 +163,17 @@ abstract class Model extends BaseModel
public function setAttribute($key, $value) public function setAttribute($key, $value)
{ {
// Convert _id to ObjectID. // Convert _id to ObjectID.
if ($key == '_id' and is_string($value)) { if ($key == '_id' && is_string($value)) {
$builder = $this->newBaseQueryBuilder(); $builder = $this->newBaseQueryBuilder();
$value = $builder->convertKey($value); $value = $builder->convertKey($value);
} // Support keys in dot notation. } // Support keys in dot notation.
elseif (str_contains($key, '.')) { elseif (Str::contains($key, '.')) {
if (in_array($key, $this->getDates()) && $value) { if (in_array($key, $this->getDates()) && $value) {
$value = $this->fromDateTime($value); $value = $this->fromDateTime($value);
} }
array_set($this->attributes, $key, $value); Arr::set($this->attributes, $key, $value);
return; return;
} }
...@@ -199,8 +200,8 @@ abstract class Model extends BaseModel ...@@ -199,8 +200,8 @@ abstract class Model extends BaseModel
// Convert dot-notation dates. // Convert dot-notation dates.
foreach ($this->getDates() as $key) { foreach ($this->getDates() as $key) {
if (str_contains($key, '.') and array_has($attributes, $key)) { if (Str::contains($key, '.') && Arr::has($attributes, $key)) {
array_set($attributes, $key, (string) $this->asDateTime(array_get($attributes, $key))); Arr::set($attributes, $key, (string) $this->asDateTime(Arr::get($attributes, $key)));
} }
} }
...@@ -218,20 +219,36 @@ abstract class Model extends BaseModel ...@@ -218,20 +219,36 @@ abstract class Model extends BaseModel
/** /**
* @inheritdoc * @inheritdoc
*/ */
protected function originalIsNumericallyEquivalent($key) protected function originalIsEquivalent($key, $current)
{ {
$current = $this->attributes[$key]; if (!array_key_exists($key, $this->original)) {
$original = $this->original[$key]; return false;
}
$original = $this->getOriginal($key);
if ($current === $original) {
return true;
}
if (null === $current) {
return false;
}
// Date comparison. if ($this->isDateAttribute($key)) {
if (in_array($key, $this->getDates())) {
$current = $current instanceof UTCDateTime ? $this->asDateTime($current) : $current; $current = $current instanceof UTCDateTime ? $this->asDateTime($current) : $current;
$original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $original; $original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $original;
return $current == $original; return $current == $original;
} }
return parent::originalIsNumericallyEquivalent($key); if ($this->hasCast($key)) {
return $this->castAttribute($key, $current) ===
$this->castAttribute($key, $original);
}
return is_numeric($current) && is_numeric($original)
&& strcmp((string) $current, (string) $original) === 0;
} }
/** /**
...@@ -242,9 +259,7 @@ abstract class Model extends BaseModel ...@@ -242,9 +259,7 @@ abstract class Model extends BaseModel
*/ */
public function drop($columns) public function drop($columns)
{ {
if (!is_array($columns)) { $columns = Arr::wrap($columns);
$columns = [$columns];
}
// Unset attributes // Unset attributes
foreach ($columns as $column) { foreach ($columns as $column) {
...@@ -263,16 +278,14 @@ abstract class Model extends BaseModel ...@@ -263,16 +278,14 @@ abstract class Model extends BaseModel
if ($parameters = func_get_args()) { if ($parameters = func_get_args()) {
$unique = false; $unique = false;
if (count($parameters) == 3) { if (count($parameters) === 3) {
list($column, $values, $unique) = $parameters; list($column, $values, $unique) = $parameters;
} else { } else {
list($column, $values) = $parameters; list($column, $values) = $parameters;
} }
// Do batch push by default. // Do batch push by default.
if (!is_array($values)) { $values = Arr::wrap($values);
$values = [$values];
}
$query = $this->setKeysForSaveQuery($this->newQuery()); $query = $this->setKeysForSaveQuery($this->newQuery());
...@@ -294,9 +307,7 @@ abstract class Model extends BaseModel ...@@ -294,9 +307,7 @@ abstract class Model extends BaseModel
public function pull($column, $values) public function pull($column, $values)
{ {
// Do batch pull by default. // Do batch pull by default.
if (!is_array($values)) { $values = Arr::wrap($values);
$values = [$values];
}
$query = $this->setKeysForSaveQuery($this->newQuery()); $query = $this->setKeysForSaveQuery($this->newQuery());
...@@ -318,11 +329,11 @@ abstract class Model extends BaseModel ...@@ -318,11 +329,11 @@ abstract class Model extends BaseModel
foreach ($values as $value) { foreach ($values as $value) {
// Don't add duplicate values when we only want unique values. // Don't add duplicate values when we only want unique values.
if ($unique and in_array($value, $current)) { if ($unique && (!is_array($current) || in_array($value, $current))) {
continue; continue;
} }
array_push($current, $value); $current[] = $value;
} }
$this->attributes[$column] = $current; $this->attributes[$column] = $current;
...@@ -340,6 +351,7 @@ abstract class Model extends BaseModel ...@@ -340,6 +351,7 @@ abstract class Model extends BaseModel
{ {
$current = $this->getAttributeFromArray($column) ?: []; $current = $this->getAttributeFromArray($column) ?: [];
if (is_array($current)) {
foreach ($values as $value) { foreach ($values as $value) {
$keys = array_keys($current, $value); $keys = array_keys($current, $value);
...@@ -347,6 +359,7 @@ abstract class Model extends BaseModel ...@@ -347,6 +359,7 @@ abstract class Model extends BaseModel
unset($current[$key]); unset($current[$key]);
} }
} }
}
$this->attributes[$column] = array_values($current); $this->attributes[$column] = array_values($current);
......
...@@ -8,6 +8,7 @@ use Illuminate\Database\Query\Builder as BaseBuilder; ...@@ -8,6 +8,7 @@ use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Expression; use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Connection; use Jenssegers\Mongodb\Connection;
use MongoCollection; use MongoCollection;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
...@@ -232,7 +233,7 @@ class Builder extends BaseBuilder ...@@ -232,7 +233,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 or $this->aggregate or $this->paginating) { if ($this->groups || $this->aggregate || $this->paginating) {
$group = []; $group = [];
$unwinds = []; $unwinds = [];
...@@ -286,7 +287,7 @@ class Builder extends BaseBuilder ...@@ -286,7 +287,7 @@ class Builder extends BaseBuilder
} }
// The _id field is mandatory when using grouping. // The _id field is mandatory when using grouping.
if ($group and empty($group['_id'])) { if ($group && empty($group['_id'])) {
$group['_id'] = null; $group['_id'] = null;
} }
...@@ -490,6 +491,24 @@ class Builder extends BaseBuilder ...@@ -490,6 +491,24 @@ class Builder extends BaseBuilder
return $this; return $this;
} }
/**
* Add a "where all" clause to the query.
*
* @param string $column
* @param array $values
* @param string $boolean
* @param bool $not
* @return $this
*/
public function whereAll($column, array $values, $boolean = 'and', $not = false)
{
$type = 'all';
$this->wheres[] = compact('column', 'type', 'boolean', 'values', 'not');
return $this;
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -563,7 +582,7 @@ class Builder extends BaseBuilder ...@@ -563,7 +582,7 @@ class Builder extends BaseBuilder
public function update(array $values, array $options = []) public function update(array $values, array $options = [])
{ {
// Use $set as default operator. // Use $set as default operator.
if (!starts_with(key($values), '$')) { if (!Str::startsWith(key($values), '$')) {
$values = ['$set' => $values]; $values = ['$set' => $values];
} }
...@@ -599,6 +618,28 @@ class Builder extends BaseBuilder ...@@ -599,6 +618,28 @@ class Builder extends BaseBuilder
return $this->increment($column, -1 * $amount, $extra, $options); return $this->increment($column, -1 * $amount, $extra, $options);
} }
/**
* @inheritdoc
*/
public function chunkById($count, callable $callback, $column = '_id', $alias = null)
{
return parent::chunkById($count, $callback, $column, $alias);
}
/**
* @inheritdoc
*/
public function forPageAfterId($perPage = 15, $lastId = 0, $column = '_id')
{
// When using ObjectIDs to paginate, we need to use a hex string as the
// "minimum" ID rather than the integer zero so the '$lt' query works.
if ($column === '_id' && $lastId === 0) {
$lastId = '000000000000000000000000';
}
return parent::forPageAfterId($perPage, $lastId, $column);
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -705,7 +746,7 @@ class Builder extends BaseBuilder ...@@ -705,7 +746,7 @@ class Builder extends BaseBuilder
$operator = $unique ? '$addToSet' : '$push'; $operator = $unique ? '$addToSet' : '$push';
// Check if we are pushing multiple values. // Check if we are pushing multiple values.
$batch = (is_array($value) and array_keys($value) === range(0, count($value) - 1)); $batch = (is_array($value) && array_keys($value) === range(0, count($value) - 1));
if (is_array($column)) { if (is_array($column)) {
$query = [$operator => $column]; $query = [$operator => $column];
...@@ -728,7 +769,7 @@ class Builder extends BaseBuilder ...@@ -728,7 +769,7 @@ class Builder extends BaseBuilder
public function pull($column, $value = null) public function pull($column, $value = null)
{ {
// Check if we passed an associative array. // Check if we passed an associative array.
$batch = (is_array($value) and array_keys($value) === range(0, count($value) - 1)); $batch = (is_array($value) && array_keys($value) === range(0, count($value) - 1));
// If we are pulling multiple values, we need to use $pullAll. // If we are pulling multiple values, we need to use $pullAll.
$operator = $batch ? '$pullAll' : '$pull'; $operator = $batch ? '$pullAll' : '$pull';
...@@ -804,7 +845,7 @@ class Builder extends BaseBuilder ...@@ -804,7 +845,7 @@ class Builder extends BaseBuilder
*/ */
public function convertKey($id) public function convertKey($id)
{ {
if (is_string($id) and strlen($id) === 24 and ctype_xdigit($id)) { if (is_string($id) && strlen($id) === 24 && ctype_xdigit($id)) {
return new ObjectID($id); return new ObjectID($id);
} }
...@@ -822,7 +863,7 @@ class Builder extends BaseBuilder ...@@ -822,7 +863,7 @@ class Builder extends BaseBuilder
if (func_num_args() == 3) { if (func_num_args() == 3) {
$operator = &$params[1]; $operator = &$params[1];
if (starts_with($operator, '$')) { if (Str::startsWith($operator, '$')) {
$operator = substr($operator, 1); $operator = substr($operator, 1);
} }
} }
...@@ -866,7 +907,7 @@ class Builder extends BaseBuilder ...@@ -866,7 +907,7 @@ class Builder extends BaseBuilder
} }
// Convert id's. // Convert id's.
if (isset($where['column']) and ($where['column'] == '_id' or ends_with($where['column'], '._id'))) { if (isset($where['column']) && ($where['column'] == '_id' || Str::endsWith($where['column'], '._id'))) {
// Multiple values. // Multiple values.
if (isset($where['values'])) { if (isset($where['values'])) {
foreach ($where['values'] as &$value) { foreach ($where['values'] as &$value) {
...@@ -891,12 +932,18 @@ class Builder extends BaseBuilder ...@@ -891,12 +932,18 @@ class Builder extends BaseBuilder
$where['value'] = new UTCDateTime($where['value']->getTimestamp() * 1000); $where['value'] = new UTCDateTime($where['value']->getTimestamp() * 1000);
} }
} }
} elseif (isset($where['values'])) {
array_walk_recursive($where['values'], function (&$item, $key) {
if ($item instanceof DateTime) {
$item = new UTCDateTime($item->getTimestamp() * 1000);
}
});
} }
// The next item in a "chain" of wheres devices the boolean of the // The next item in a "chain" of wheres devices the boolean of the
// first item. So if we see that there are multiple wheres, we will // first item. So if we see that there are multiple wheres, we will
// use the operator of the next where. // use the operator of the next where.
if ($i == 0 and count($wheres) > 1 and $where['boolean'] == 'and') { if ($i == 0 && count($wheres) > 1 && $where['boolean'] == 'and') {
$where['boolean'] = $wheres[$i + 1]['boolean']; $where['boolean'] = $wheres[$i + 1]['boolean'];
} }
...@@ -922,6 +969,17 @@ class Builder extends BaseBuilder ...@@ -922,6 +969,17 @@ class Builder extends BaseBuilder
return $compiled; return $compiled;
} }
/**
* @param array $where
* @return array
*/
protected function compileWhereAll(array $where)
{
extract($where);
return [$column => ['$all' => array_values($values)]];
}
/** /**
* @param array $where * @param array $where
* @return array * @return array
...@@ -938,10 +996,10 @@ class Builder extends BaseBuilder ...@@ -938,10 +996,10 @@ class Builder extends BaseBuilder
$regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value)); $regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value));
// Convert like to regular expression. // Convert like to regular expression.
if (!starts_with($value, '%')) { if (!Str::startsWith($value, '%')) {
$regex = '^' . $regex; $regex = '^' . $regex;
} }
if (!ends_with($value, '%')) { if (!Str::endsWith($value, '%')) {
$regex = $regex . '$'; $regex = $regex . '$';
} }
...@@ -958,12 +1016,12 @@ class Builder extends BaseBuilder ...@@ -958,12 +1016,12 @@ class Builder extends BaseBuilder
// For inverse regexp operations, we can just use the $not operator // For inverse regexp operations, we can just use the $not operator
// and pass it a Regex instence. // and pass it a Regex instence.
if (starts_with($operator, 'not')) { if (Str::startsWith($operator, 'not')) {
$operator = 'not'; $operator = 'not';
} }
} }
if (!isset($operator) or $operator == '=') { if (!isset($operator) || $operator == '=') {
$query = [$column => $value]; $query = [$column => $value];
} elseif (array_key_exists($operator, $this->conversion)) { } elseif (array_key_exists($operator, $this->conversion)) {
$query = [$column => [$this->conversion[$operator] => $value]]; $query = [$column => [$this->conversion[$operator] => $value]];
......
...@@ -117,7 +117,7 @@ class MongoQueue extends DatabaseQueue ...@@ -117,7 +117,7 @@ class MongoQueue extends DatabaseQueue
})->get(); })->get();
foreach ($reserved as $job) { foreach ($reserved as $job) {
$attempts = $job['attempts'] + 1; $attempts = $job['attempts'];
$this->releaseJob($job['_id'], $attempts); $this->releaseJob($job['_id'], $attempts);
} }
} }
......
...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder; ...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany;
use Illuminate\Support\Arr;
class BelongsToMany extends EloquentBelongsToMany class BelongsToMany extends EloquentBelongsToMany
{ {
...@@ -93,7 +94,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -93,7 +94,7 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function create(array $attributes, array $joining = [], $touch = true) public function create(array $attributes = [], array $joining = [], $touch = true)
{ {
$instance = $this->related->newInstance($attributes); $instance = $this->related->newInstance($attributes);
...@@ -134,6 +135,8 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -134,6 +135,8 @@ class BelongsToMany extends EloquentBelongsToMany
$records = $this->formatSyncList($ids); $records = $this->formatSyncList($ids);
$current = Arr::wrap($current);
$detach = array_diff($current, array_keys($records)); $detach = array_diff($current, array_keys($records));
// We need to make sure we pass a clean array, so that it is not interpreted // We need to make sure we pass a clean array, so that it is not interpreted
...@@ -143,7 +146,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -143,7 +146,7 @@ class BelongsToMany extends EloquentBelongsToMany
// Next, we will take the differences of the currents and given IDs and detach // Next, we will take the differences of the currents and given IDs and detach
// all of the entities that exist in the "current" array but are not in the // all of the entities that exist in the "current" array but are not in the
// the array of the IDs given to the method which will complete the sync. // the array of the IDs given to the method which will complete the sync.
if ($detaching and count($detach) > 0) { if ($detaching && count($detach) > 0) {
$this->detach($detach); $this->detach($detach);
$changes['detached'] = (array) array_map(function ($v) { $changes['detached'] = (array) array_map(function ($v) {
...@@ -184,7 +187,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -184,7 +187,7 @@ class BelongsToMany extends EloquentBelongsToMany
$id = $model->getKey(); $id = $model->getKey();
// Attach the new parent id to the related model. // Attach the new parent id to the related model.
$model->push($this->foreignKey, $this->parent->getKey(), true); $model->push($this->foreignPivotKey, $this->parent->getKey(), true);
} else { } else {
if ($id instanceof Collection) { if ($id instanceof Collection) {
$id = $id->modelKeys(); $id = $id->modelKeys();
...@@ -195,7 +198,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -195,7 +198,7 @@ class BelongsToMany extends EloquentBelongsToMany
$query->whereIn($this->related->getKeyName(), (array) $id); $query->whereIn($this->related->getKeyName(), (array) $id);
// Attach the new parent id to the related model. // Attach the new parent id to the related model.
$query->push($this->foreignKey, $this->parent->getKey(), true); $query->push($this->foreignPivotKey, $this->parent->getKey(), true);
} }
// Attach the new ids to the parent model. // Attach the new ids to the parent model.
...@@ -231,7 +234,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -231,7 +234,7 @@ class BelongsToMany extends EloquentBelongsToMany
} }
// Remove the relation to the parent. // Remove the relation to the parent.
$query->pull($this->foreignKey, $this->parent->getKey()); $query->pull($this->foreignPivotKey, $this->parent->getKey());
if ($touch) { if ($touch) {
$this->touchIfTouching(); $this->touchIfTouching();
...@@ -245,7 +248,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -245,7 +248,7 @@ class BelongsToMany extends EloquentBelongsToMany
*/ */
protected function buildDictionary(Collection $results) protected function buildDictionary(Collection $results)
{ {
$foreign = $this->foreignKey; $foreign = $this->foreignPivotKey;
// First we will build a dictionary of child models keyed by the foreign key // First we will build a dictionary of child models keyed by the foreign key
// of the relation so that we will easily and quickly match them to their // of the relation so that we will easily and quickly match them to their
...@@ -286,15 +289,23 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -286,15 +289,23 @@ class BelongsToMany extends EloquentBelongsToMany
*/ */
public function getForeignKey() public function getForeignKey()
{ {
return $this->foreignKey; return $this->foreignPivotKey;
}
/**
* @inheritdoc
*/
public function getQualifiedForeignPivotKeyName()
{
return $this->foreignPivotKey;
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getQualifiedForeignKeyName() public function getQualifiedRelatedPivotKeyName()
{ {
return $this->foreignKey; return $this->relatedPivotKey;
} }
/** /**
...@@ -324,6 +335,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -324,6 +335,6 @@ class BelongsToMany extends EloquentBelongsToMany
*/ */
public function getRelatedKey() public function getRelatedKey()
{ {
return property_exists($this, 'relatedKey') ? $this->relatedKey : $this->otherKey; return property_exists($this, 'relatedPivotKey') ? $this->relatedPivotKey : $this->relatedKey;
} }
} }
...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Collection; ...@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator; use Illuminate\Pagination\Paginator;
use Illuminate\Support\Arr;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
class EmbedsMany extends EmbedsOneOrMany class EmbedsMany extends EmbedsOneOrMany
...@@ -39,7 +40,7 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -39,7 +40,7 @@ class EmbedsMany extends EmbedsOneOrMany
public function performInsert(Model $model) public function performInsert(Model $model)
{ {
// Generate a new key if needed. // Generate a new key if needed.
if ($model->getKeyName() == '_id' and !$model->getKey()) { if ($model->getKeyName() == '_id' && !$model->getKey()) {
$model->setAttribute('_id', new ObjectID); $model->setAttribute('_id', new ObjectID);
} }
...@@ -79,7 +80,7 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -79,7 +80,7 @@ class EmbedsMany extends EmbedsOneOrMany
$foreignKey = $this->getForeignKeyValue($model); $foreignKey = $this->getForeignKeyValue($model);
// Use array dot notation for better update behavior. // Use array dot notation for better update behavior.
$values = array_dot($model->getDirty(), $this->localKey . '.$.'); $values = Arr::dot($model->getDirty(), $this->localKey . '.$.');
// Update document in database. // Update document in database.
$result = $this->getBaseQuery()->where($this->localKey . '.' . $model->getKeyName(), $foreignKey) $result = $this->getBaseQuery()->where($this->localKey . '.' . $model->getKeyName(), $foreignKey)
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
class EmbedsOne extends EmbedsOneOrMany class EmbedsOne extends EmbedsOneOrMany
...@@ -36,7 +37,7 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -36,7 +37,7 @@ class EmbedsOne extends EmbedsOneOrMany
public function performInsert(Model $model) public function performInsert(Model $model)
{ {
// Generate a new key if needed. // Generate a new key if needed.
if ($model->getKeyName() == '_id' and !$model->getKey()) { if ($model->getKeyName() == '_id' && !$model->getKey()) {
$model->setAttribute('_id', new ObjectID); $model->setAttribute('_id', new ObjectID);
} }
...@@ -71,7 +72,7 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -71,7 +72,7 @@ class EmbedsOne extends EmbedsOneOrMany
} }
// Use array dot notation for better update behavior. // Use array dot notation for better update behavior.
$values = array_dot($model->getDirty(), $this->localKey . '.'); $values = Arr::dot($model->getDirty(), $this->localKey . '.');
$result = $this->getBaseQuery()->update($values); $result = $this->getBaseQuery()->update($values);
......
...@@ -94,9 +94,11 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -94,9 +94,11 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Shorthand to get the results of the relationship. * Shorthand to get the results of the relationship.
* *
* @param array $columns
*
* @return Collection * @return Collection
*/ */
public function get() public function get($columns = ['*'])
{ {
return $this->getResults(); return $this->getResults();
} }
...@@ -265,7 +267,7 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -265,7 +267,7 @@ abstract class EmbedsOneOrMany extends Relation
$models = $this->eagerLoadRelations($models); $models = $this->eagerLoadRelations($models);
} }
return new Collection($models); return $this->related->newCollection($models);
} }
/** /**
...@@ -280,7 +282,12 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -280,7 +282,12 @@ abstract class EmbedsOneOrMany extends Relation
return; return;
} }
$model = $this->related->newFromBuilder((array) $attributes); $connection = $this->related->getConnection();
$model = $this->related->newFromBuilder(
(array) $attributes,
$connection ? $connection->getName() : null
);
$model->setParentRelation($this); $model->setParentRelation($this);
......
...@@ -156,7 +156,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -156,7 +156,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
*/ */
public function geospatial($columns = null, $index = '2d', $options = []) public function geospatial($columns = null, $index = '2d', $options = [])
{ {
if ($index == '2d' or $index == '2dsphere') { if ($index == '2d' || $index == '2dsphere') {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
$columns = array_flip($columns); $columns = array_flip($columns);
......
...@@ -106,6 +106,16 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -106,6 +106,16 @@ class Builder extends \Illuminate\Database\Schema\Builder
return $blueprint->drop(); return $blueprint->drop();
} }
/**
* @inheritdoc
*/
public function dropAllTables()
{
foreach ($this->getAllCollections() as $collection) {
$this->drop($collection);
}
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -113,4 +123,19 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -113,4 +123,19 @@ class Builder extends \Illuminate\Database\Schema\Builder
{ {
return new Blueprint($this->connection, $collection); return new Blueprint($this->connection, $collection);
} }
/**
* Get all of the collections names for the database.
*
* @return array
*/
protected function getAllCollections()
{
$collections = [];
foreach ($this->connection->getMongoDB()->listCollections() as $collection) {
$collections[] = $collection->getName();
}
return $collections;
}
} }
...@@ -44,7 +44,7 @@ class ConnectionTest extends TestCase ...@@ -44,7 +44,7 @@ class ConnectionTest extends TestCase
// public function testDynamic() // public function testDynamic()
// { // {
// $dbs = DB::connection('mongodb')->listCollections(); // $dbs = DB::connection('mongodb')->listCollections();
// $this->assertTrue(is_array($dbs)); // $this->assertInternalType('array', $dbs);
// } // }
// public function testMultipleConnections() // public function testMultipleConnections()
...@@ -59,29 +59,29 @@ class ConnectionTest extends TestCase ...@@ -59,29 +59,29 @@ class ConnectionTest extends TestCase
// $mongoclient = $connection->getMongoClient(); // $mongoclient = $connection->getMongoClient();
// $hosts = $mongoclient->getHosts(); // $hosts = $mongoclient->getHosts();
// $this->assertEquals(1, count($hosts)); // $this->assertCount(1, $hosts);
// } // }
public function testQueryLog() public function testQueryLog()
{ {
DB::enableQueryLog(); DB::enableQueryLog();
$this->assertEquals(0, count(DB::getQueryLog())); $this->assertCount(0, DB::getQueryLog());
DB::collection('items')->get(); DB::collection('items')->get();
$this->assertEquals(1, count(DB::getQueryLog())); $this->assertCount(1, DB::getQueryLog());
DB::collection('items')->insert(['name' => 'test']); DB::collection('items')->insert(['name' => 'test']);
$this->assertEquals(2, count(DB::getQueryLog())); $this->assertCount(2, DB::getQueryLog());
DB::collection('items')->count(); DB::collection('items')->count();
$this->assertEquals(3, count(DB::getQueryLog())); $this->assertCount(3, DB::getQueryLog());
DB::collection('items')->where('name', 'test')->update(['name' => 'test']); DB::collection('items')->where('name', 'test')->update(['name' => 'test']);
$this->assertEquals(4, count(DB::getQueryLog())); $this->assertCount(4, DB::getQueryLog());
DB::collection('items')->where('name', 'test')->delete(); DB::collection('items')->where('name', 'test')->delete();
$this->assertEquals(5, count(DB::getQueryLog())); $this->assertCount(5, DB::getQueryLog());
} }
public function testSchemaBuilder() public function testSchemaBuilder()
...@@ -98,12 +98,13 @@ class ConnectionTest extends TestCase ...@@ -98,12 +98,13 @@ class ConnectionTest extends TestCase
public function testAuth() public function testAuth()
{ {
$host = Config::get('database.connections.mongodb.host');
Config::set('database.connections.mongodb.username', 'foo'); Config::set('database.connections.mongodb.username', 'foo');
Config::set('database.connections.mongodb.password', 'bar'); Config::set('database.connections.mongodb.password', 'bar');
Config::set('database.connections.mongodb.options.database', 'custom'); Config::set('database.connections.mongodb.options.database', 'custom');
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertEquals('mongodb://127.0.0.1/custom', (string) $connection->getMongoClient()); $this->assertEquals('mongodb://' . $host . '/custom', (string) $connection->getMongoClient());
} }
public function testCustomHostAndPort() public function testCustomHostAndPort()
......
This diff is collapsed.
...@@ -27,13 +27,13 @@ class HybridRelationsTest extends TestCase ...@@ -27,13 +27,13 @@ class HybridRelationsTest extends TestCase
// Mysql User // Mysql User
$user->name = "John Doe"; $user->name = "John Doe";
$user->save(); $user->save();
$this->assertTrue(is_int($user->id)); $this->assertInternalType('int', $user->id);
// SQL has many // SQL has many
$book = new Book(['title' => 'Game of Thrones']); $book = new Book(['title' => 'Game of Thrones']);
$user->books()->save($book); $user->books()->save($book);
$user = MysqlUser::find($user->id); // refetch $user = MysqlUser::find($user->id); // refetch
$this->assertEquals(1, count($user->books)); $this->assertCount(1, $user->books);
// MongoDB belongs to // MongoDB belongs to
$book = $user->books()->first(); // refetch $book = $user->books()->first(); // refetch
...@@ -58,7 +58,7 @@ class HybridRelationsTest extends TestCase ...@@ -58,7 +58,7 @@ class HybridRelationsTest extends TestCase
$book = new MysqlBook(['title' => 'Game of Thrones']); $book = new MysqlBook(['title' => 'Game of Thrones']);
$user->mysqlBooks()->save($book); $user->mysqlBooks()->save($book);
$user = User::find($user->_id); // refetch $user = User::find($user->_id); // refetch
$this->assertEquals(1, count($user->mysqlBooks)); $this->assertCount(1, $user->mysqlBooks);
// SQL belongs to // SQL belongs to
$book = $user->mysqlBooks()->first(); // refetch $book = $user->mysqlBooks()->first(); // refetch
...@@ -93,8 +93,8 @@ class HybridRelationsTest extends TestCase ...@@ -93,8 +93,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3; $otherUser->id = 3;
$otherUser->save(); $otherUser->save();
// Make sure they are created // Make sure they are created
$this->assertTrue(is_int($user->id)); $this->assertInternalType('int', $user->id);
$this->assertTrue(is_int($otherUser->id)); $this->assertInternalType('int', $otherUser->id);
// Clear to start // Clear to start
$user->books()->truncate(); $user->books()->truncate();
$otherUser->books()->truncate(); $otherUser->books()->truncate();
...@@ -147,8 +147,8 @@ class HybridRelationsTest extends TestCase ...@@ -147,8 +147,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3; $otherUser->id = 3;
$otherUser->save(); $otherUser->save();
// Make sure they are created // Make sure they are created
$this->assertTrue(is_int($user->id)); $this->assertInternalType('int', $user->id);
$this->assertTrue(is_int($otherUser->id)); $this->assertInternalType('int', $otherUser->id);
// Clear to start // Clear to start
Book::truncate(); Book::truncate();
MysqlBook::truncate(); MysqlBook::truncate();
......
...@@ -21,7 +21,7 @@ class ModelTest extends TestCase ...@@ -21,7 +21,7 @@ class ModelTest extends TestCase
$user = new User; $user = new User;
$this->assertInstanceOf(Model::class, $user); $this->assertInstanceOf(Model::class, $user);
$this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection()); $this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection());
$this->assertEquals(false, $user->exists); $this->assertFalse($user->exists);
$this->assertEquals('users', $user->getTable()); $this->assertEquals('users', $user->getTable());
$this->assertEquals('_id', $user->getKeyName()); $this->assertEquals('_id', $user->getKeyName());
} }
...@@ -35,11 +35,11 @@ class ModelTest extends TestCase ...@@ -35,11 +35,11 @@ class ModelTest extends TestCase
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
$this->assertTrue(isset($user->_id)); $this->assertTrue(isset($user->_id));
$this->assertTrue(is_string($user->_id)); $this->assertInternalType('string', $user->_id);
$this->assertNotEquals('', (string) $user->_id); $this->assertNotEquals('', (string) $user->_id);
$this->assertNotEquals(0, strlen((string) $user->_id)); $this->assertNotEquals(0, strlen((string) $user->_id));
$this->assertInstanceOf(Carbon::class, $user->created_at); $this->assertInstanceOf(Carbon::class, $user->created_at);
...@@ -67,7 +67,7 @@ class ModelTest extends TestCase ...@@ -67,7 +67,7 @@ class ModelTest extends TestCase
$check->age = 36; $check->age = 36;
$check->save(); $check->save();
$this->assertEquals(true, $check->exists); $this->assertTrue($check->exists);
$this->assertInstanceOf(Carbon::class, $check->created_at); $this->assertInstanceOf(Carbon::class, $check->created_at);
$this->assertInstanceOf(Carbon::class, $check->updated_at); $this->assertInstanceOf(Carbon::class, $check->updated_at);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
...@@ -93,7 +93,7 @@ class ModelTest extends TestCase ...@@ -93,7 +93,7 @@ class ModelTest extends TestCase
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id); $this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
...@@ -106,7 +106,7 @@ class ModelTest extends TestCase ...@@ -106,7 +106,7 @@ class ModelTest extends TestCase
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals('customId', $user->_id); $this->assertEquals('customId', $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
...@@ -122,7 +122,7 @@ class ModelTest extends TestCase ...@@ -122,7 +122,7 @@ class ModelTest extends TestCase
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals(1, $user->_id); $this->assertEquals(1, $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
...@@ -137,7 +137,7 @@ class ModelTest extends TestCase ...@@ -137,7 +137,7 @@ class ModelTest extends TestCase
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
$user->delete(); $user->delete();
...@@ -161,7 +161,7 @@ class ModelTest extends TestCase ...@@ -161,7 +161,7 @@ class ModelTest extends TestCase
$all = User::all(); $all = User::all();
$this->assertEquals(2, count($all)); $this->assertCount(2, $all);
$this->assertContains('John Doe', $all->pluck('name')); $this->assertContains('John Doe', $all->pluck('name'));
$this->assertContains('Jane Doe', $all->pluck('name')); $this->assertContains('Jane Doe', $all->pluck('name'));
} }
...@@ -177,7 +177,7 @@ class ModelTest extends TestCase ...@@ -177,7 +177,7 @@ class ModelTest extends TestCase
$check = User::find($user->_id); $check = User::find($user->_id);
$this->assertInstanceOf(Model::class, $check); $this->assertInstanceOf(Model::class, $check);
$this->assertEquals(true, $check->exists); $this->assertTrue($check->exists);
$this->assertEquals($user->_id, $check->_id); $this->assertEquals($user->_id, $check->_id);
$this->assertEquals('John Doe', $check->name); $this->assertEquals('John Doe', $check->name);
...@@ -192,7 +192,7 @@ class ModelTest extends TestCase ...@@ -192,7 +192,7 @@ class ModelTest extends TestCase
]); ]);
$users = User::get(); $users = User::get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$this->assertInstanceOf(Collection::class, $users); $this->assertInstanceOf(Collection::class, $users);
$this->assertInstanceOf(Model::class, $users[0]); $this->assertInstanceOf(Model::class, $users[0]);
} }
...@@ -216,10 +216,10 @@ class ModelTest extends TestCase ...@@ -216,10 +216,10 @@ class ModelTest extends TestCase
$this->assertEquals(0, $items->count()); $this->assertEquals(0, $items->count());
$item = Item::where('name', 'nothing')->first(); $item = Item::where('name', 'nothing')->first();
$this->assertEquals(null, $item); $this->assertNull($item);
$item = Item::find('51c33d8981fec6813e00000a'); $item = Item::find('51c33d8981fec6813e00000a');
$this->assertEquals(null, $item); $this->assertNull($item);
} }
public function testFindOrfail() public function testFindOrfail()
...@@ -233,7 +233,7 @@ class ModelTest extends TestCase ...@@ -233,7 +233,7 @@ class ModelTest extends TestCase
$user = User::create(['name' => 'Jane Poe']); $user = User::create(['name' => 'Jane Poe']);
$this->assertInstanceOf(Model::class, $user); $this->assertInstanceOf(Model::class, $user);
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals('Jane Poe', $user->name); $this->assertEquals('Jane Poe', $user->name);
$check = User::where('name', 'Jane Poe')->first(); $check = User::where('name', 'Jane Poe')->first();
...@@ -278,12 +278,12 @@ class ModelTest extends TestCase ...@@ -278,12 +278,12 @@ class ModelTest extends TestCase
$this->assertEquals(2, Soft::count()); $this->assertEquals(2, Soft::count());
$user = Soft::where('name', 'John Doe')->first(); $user = Soft::where('name', 'John Doe')->first();
$this->assertEquals(true, $user->exists); $this->assertTrue($user->exists);
$this->assertEquals(false, $user->trashed()); $this->assertFalse($user->trashed());
$this->assertNull($user->deleted_at); $this->assertNull($user->deleted_at);
$user->delete(); $user->delete();
$this->assertEquals(true, $user->trashed()); $this->assertTrue($user->trashed());
$this->assertNotNull($user->deleted_at); $this->assertNotNull($user->deleted_at);
$user = Soft::where('name', 'John Doe')->first(); $user = Soft::where('name', 'John Doe')->first();
...@@ -295,7 +295,7 @@ class ModelTest extends TestCase ...@@ -295,7 +295,7 @@ class ModelTest extends TestCase
$user = Soft::withTrashed()->where('name', 'John Doe')->first(); $user = Soft::withTrashed()->where('name', 'John Doe')->first();
$this->assertNotNull($user); $this->assertNotNull($user);
$this->assertInstanceOf(Carbon::class, $user->deleted_at); $this->assertInstanceOf(Carbon::class, $user->deleted_at);
$this->assertEquals(true, $user->trashed()); $this->assertTrue($user->trashed());
$user->restore(); $user->restore();
$this->assertEquals(2, Soft::count()); $this->assertEquals(2, Soft::count());
...@@ -340,9 +340,9 @@ class ModelTest extends TestCase ...@@ -340,9 +340,9 @@ class ModelTest extends TestCase
$keys = array_keys($array); $keys = array_keys($array);
sort($keys); sort($keys);
$this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys); $this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys);
$this->assertTrue(is_string($array['created_at'])); $this->assertInternalType('string', $array['created_at']);
$this->assertTrue(is_string($array['updated_at'])); $this->assertInternalType('string', $array['updated_at']);
$this->assertTrue(is_string($array['_id'])); $this->assertInternalType('string', $array['_id']);
} }
public function testUnset() public function testUnset()
...@@ -352,7 +352,7 @@ class ModelTest extends TestCase ...@@ -352,7 +352,7 @@ class ModelTest extends TestCase
$user1->unset('note1'); $user1->unset('note1');
$this->assertFalse(isset($user1->note1)); $this->assertObjectNotHasAttribute('note1', $user1);
$this->assertTrue(isset($user1->note2)); $this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1)); $this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2)); $this->assertTrue(isset($user2->note2));
...@@ -361,15 +361,15 @@ class ModelTest extends TestCase ...@@ -361,15 +361,15 @@ class ModelTest extends TestCase
$user1 = User::find($user1->_id); $user1 = User::find($user1->_id);
$user2 = User::find($user2->_id); $user2 = User::find($user2->_id);
$this->assertFalse(isset($user1->note1)); $this->assertObjectNotHasAttribute('note1', $user1);
$this->assertTrue(isset($user1->note2)); $this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1)); $this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2)); $this->assertTrue(isset($user2->note2));
$user2->unset(['note1', 'note2']); $user2->unset(['note1', 'note2']);
$this->assertFalse(isset($user2->note1)); $this->assertObjectNotHasAttribute('note1', $user2);
$this->assertFalse(isset($user2->note2)); $this->assertObjectNotHasAttribute('note2', $user2);
} }
public function testDates() public function testDates()
...@@ -396,7 +396,7 @@ class ModelTest extends TestCase ...@@ -396,7 +396,7 @@ class ModelTest extends TestCase
$this->assertEquals($item->getOriginal('created_at') $this->assertEquals($item->getOriginal('created_at')
->toDateTime() ->toDateTime()
->getTimestamp(), $item->created_at->getTimestamp()); ->getTimestamp(), $item->created_at->getTimestamp());
$this->assertTrue(abs(time() - $item->created_at->getTimestamp()) < 2); $this->assertLessThan(2, abs(time() - $item->created_at->getTimestamp()));
// test default date format for json output // test default date format for json output
$item = Item::create(['name' => 'sword']); $item = Item::create(['name' => 'sword']);
...@@ -534,4 +534,18 @@ class ModelTest extends TestCase ...@@ -534,4 +534,18 @@ class ModelTest extends TestCase
$user->birthday = new DateTime('19 august 1989'); $user->birthday = new DateTime('19 august 1989');
$this->assertEmpty($user->getDirty()); $this->assertEmpty($user->getDirty());
} }
public function testChunkById()
{
User::create(['name' => 'fork', 'tags' => ['sharp', 'pointy']]);
User::create(['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']]);
User::create(['name' => 'spoon', 'tags' => ['round', 'bowl']]);
$count = 0;
User::chunkById(2, function ($items) use (&$count) {
$count += count($items);
});
$this->assertEquals(3, $count);
}
} }
This diff is collapsed.
...@@ -27,46 +27,46 @@ class QueryTest extends TestCase ...@@ -27,46 +27,46 @@ class QueryTest extends TestCase
public function testWhere() public function testWhere()
{ {
$users = User::where('age', 35)->get(); $users = User::where('age', 35)->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
$users = User::where('age', '=', 35)->get(); $users = User::where('age', '=', 35)->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
$users = User::where('age', '>=', 35)->get(); $users = User::where('age', '>=', 35)->get();
$this->assertEquals(4, count($users)); $this->assertCount(4, $users);
$users = User::where('age', '<=', 18)->get(); $users = User::where('age', '<=', 18)->get();
$this->assertEquals(1, count($users)); $this->assertCount(1, $users);
$users = User::where('age', '!=', 35)->get(); $users = User::where('age', '!=', 35)->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
$users = User::where('age', '<>', 35)->get(); $users = User::where('age', '<>', 35)->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
} }
public function testAndWhere() public function testAndWhere()
{ {
$users = User::where('age', 35)->where('title', 'admin')->get(); $users = User::where('age', 35)->where('title', 'admin')->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::where('age', '>=', 35)->where('title', 'user')->get(); $users = User::where('age', '>=', 35)->where('title', 'user')->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
} }
public function testLike() public function testLike()
{ {
$users = User::where('name', 'like', '%doe')->get(); $users = User::where('name', 'like', '%doe')->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::where('name', 'like', '%y%')->get(); $users = User::where('name', 'like', '%y%')->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
$users = User::where('name', 'LIKE', '%y%')->get(); $users = User::where('name', 'LIKE', '%y%')->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
$users = User::where('name', 'like', 't%')->get(); $users = User::where('name', 'like', 't%')->get();
$this->assertEquals(1, count($users)); $this->assertCount(1, $users);
} }
public function testSelect() public function testSelect()
...@@ -74,75 +74,75 @@ class QueryTest extends TestCase ...@@ -74,75 +74,75 @@ class QueryTest extends TestCase
$user = User::where('name', 'John Doe')->select('name')->first(); $user = User::where('name', 'John Doe')->select('name')->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age); $this->assertNull($user->age);
$this->assertEquals(null, $user->title); $this->assertNull($user->title);
$user = User::where('name', 'John Doe')->select('name', 'title')->first(); $user = User::where('name', 'John Doe')->select('name', 'title')->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals('admin', $user->title); $this->assertEquals('admin', $user->title);
$this->assertEquals(null, $user->age); $this->assertNull($user->age);
$user = User::where('name', 'John Doe')->select(['name', 'title'])->get()->first(); $user = User::where('name', 'John Doe')->select(['name', 'title'])->get()->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals('admin', $user->title); $this->assertEquals('admin', $user->title);
$this->assertEquals(null, $user->age); $this->assertNull($user->age);
$user = User::where('name', 'John Doe')->get(['name'])->first(); $user = User::where('name', 'John Doe')->get(['name'])->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age); $this->assertNull($user->age);
} }
public function testOrWhere() public function testOrWhere()
{ {
$users = User::where('age', 13)->orWhere('title', 'admin')->get(); $users = User::where('age', 13)->orWhere('title', 'admin')->get();
$this->assertEquals(4, count($users)); $this->assertCount(4, $users);
$users = User::where('age', 13)->orWhere('age', 23)->get(); $users = User::where('age', 13)->orWhere('age', 23)->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
} }
public function testBetween() public function testBetween()
{ {
$users = User::whereBetween('age', [0, 25])->get(); $users = User::whereBetween('age', [0, 25])->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::whereBetween('age', [13, 23])->get(); $users = User::whereBetween('age', [13, 23])->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
// testing whereNotBetween for version 4.1 // testing whereNotBetween for version 4.1
$users = User::whereBetween('age', [0, 25], 'and', true)->get(); $users = User::whereBetween('age', [0, 25], 'and', true)->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
} }
public function testIn() public function testIn()
{ {
$users = User::whereIn('age', [13, 23])->get(); $users = User::whereIn('age', [13, 23])->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::whereIn('age', [33, 35, 13])->get(); $users = User::whereIn('age', [33, 35, 13])->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
$users = User::whereNotIn('age', [33, 35])->get(); $users = User::whereNotIn('age', [33, 35])->get();
$this->assertEquals(4, count($users)); $this->assertCount(4, $users);
$users = User::whereNotNull('age') $users = User::whereNotNull('age')
->whereNotIn('age', [33, 35])->get(); ->whereNotIn('age', [33, 35])->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
} }
public function testWhereNull() public function testWhereNull()
{ {
$users = User::whereNull('age')->get(); $users = User::whereNull('age')->get();
$this->assertEquals(1, count($users)); $this->assertCount(1, $users);
} }
public function testWhereNotNull() public function testWhereNotNull()
{ {
$users = User::whereNotNull('age')->get(); $users = User::whereNotNull('age')->get();
$this->assertEquals(8, count($users)); $this->assertCount(8, $users);
} }
public function testOrder() public function testOrder()
...@@ -169,16 +169,16 @@ class QueryTest extends TestCase ...@@ -169,16 +169,16 @@ class QueryTest extends TestCase
public function testGroupBy() public function testGroupBy()
{ {
$users = User::groupBy('title')->get(); $users = User::groupBy('title')->get();
$this->assertEquals(3, count($users)); $this->assertCount(3, $users);
$users = User::groupBy('age')->get(); $users = User::groupBy('age')->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
$users = User::groupBy('age')->skip(1)->get(); $users = User::groupBy('age')->skip(1)->get();
$this->assertEquals(5, count($users)); $this->assertCount(5, $users);
$users = User::groupBy('age')->take(2)->get(); $users = User::groupBy('age')->take(2)->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::groupBy('age')->orderBy('age', 'desc')->get(); $users = User::groupBy('age')->orderBy('age', 'desc')->get();
$this->assertEquals(37, $users[0]->age); $this->assertEquals(37, $users[0]->age);
...@@ -186,13 +186,13 @@ class QueryTest extends TestCase ...@@ -186,13 +186,13 @@ class QueryTest extends TestCase
$this->assertEquals(33, $users[2]->age); $this->assertEquals(33, $users[2]->age);
$users = User::groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get(); $users = User::groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$this->assertEquals(35, $users[0]->age); $this->assertEquals(35, $users[0]->age);
$this->assertEquals(33, $users[1]->age); $this->assertEquals(33, $users[1]->age);
$this->assertNull($users[0]->name); $this->assertNull($users[0]->name);
$users = User::select('name')->groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get(); $users = User::select('name')->groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$this->assertNotNull($users[0]->name); $this->assertNotNull($users[0]->name);
} }
...@@ -220,7 +220,7 @@ class QueryTest extends TestCase ...@@ -220,7 +220,7 @@ class QueryTest extends TestCase
}) })
->get(); ->get();
$this->assertEquals(5, count($users)); $this->assertCount(5, $users);
$users = User::where('title', 'user')->where(function ($query) { $users = User::where('title', 'user')->where(function ($query) {
$query->where('age', 35) $query->where('age', 35)
...@@ -228,7 +228,7 @@ class QueryTest extends TestCase ...@@ -228,7 +228,7 @@ class QueryTest extends TestCase
}) })
->get(); ->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::where('age', 35)->orWhere(function ($query) { $users = User::where('age', 35)->orWhere(function ($query) {
$query->where('title', 'admin') $query->where('title', 'admin')
...@@ -236,7 +236,7 @@ class QueryTest extends TestCase ...@@ -236,7 +236,7 @@ class QueryTest extends TestCase
}) })
->get(); ->get();
$this->assertEquals(5, count($users)); $this->assertCount(5, $users);
$users = User::whereNull('deleted_at') $users = User::whereNull('deleted_at')
->where('title', 'admin') ->where('title', 'admin')
...@@ -266,13 +266,13 @@ class QueryTest extends TestCase ...@@ -266,13 +266,13 @@ class QueryTest extends TestCase
$where = ['age' => ['$gt' => 30, '$lt' => 40]]; $where = ['age' => ['$gt' => 30, '$lt' => 40]];
$users = User::whereRaw($where)->get(); $users = User::whereRaw($where)->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
$where1 = ['age' => ['$gt' => 30, '$lte' => 35]]; $where1 = ['age' => ['$gt' => 30, '$lte' => 35]];
$where2 = ['age' => ['$gt' => 35, '$lt' => 40]]; $where2 = ['age' => ['$gt' => 35, '$lt' => 40]];
$users = User::whereRaw($where1)->orWhereRaw($where2)->get(); $users = User::whereRaw($where1)->orWhereRaw($where2)->get();
$this->assertEquals(6, count($users)); $this->assertCount(6, $users);
} }
public function testMultipleOr() public function testMultipleOr()
...@@ -284,7 +284,7 @@ class QueryTest extends TestCase ...@@ -284,7 +284,7 @@ class QueryTest extends TestCase
$query->where('name', 'John Doe')->orWhere('name', 'Jane Doe'); $query->where('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get(); })->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
$users = User::where(function ($query) { $users = User::where(function ($query) {
$query->orWhere('age', 35)->orWhere('age', 33); $query->orWhere('age', 35)->orWhere('age', 33);
...@@ -293,7 +293,7 @@ class QueryTest extends TestCase ...@@ -293,7 +293,7 @@ class QueryTest extends TestCase
$query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe'); $query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get(); })->get();
$this->assertEquals(2, count($users)); $this->assertCount(2, $users);
} }
public function testPaginate() public function testPaginate()
......
...@@ -24,7 +24,7 @@ class RelationsTest extends TestCase ...@@ -24,7 +24,7 @@ class RelationsTest extends TestCase
Book::create(['title' => 'A Clash of Kings', 'author_id' => $author->_id]); Book::create(['title' => 'A Clash of Kings', 'author_id' => $author->_id]);
$books = $author->books; $books = $author->books;
$this->assertEquals(2, count($books)); $this->assertCount(2, $books);
$user = User::create(['name' => 'John Doe']); $user = User::create(['name' => 'John Doe']);
Item::create(['type' => 'knife', 'user_id' => $user->_id]); Item::create(['type' => 'knife', 'user_id' => $user->_id]);
...@@ -33,7 +33,7 @@ class RelationsTest extends TestCase ...@@ -33,7 +33,7 @@ class RelationsTest extends TestCase
Item::create(['type' => 'bag', 'user_id' => null]); Item::create(['type' => 'bag', 'user_id' => null]);
$items = $user->items; $items = $user->items;
$this->assertEquals(3, count($items)); $this->assertCount(3, $items);
} }
public function testBelongsTo() public function testBelongsTo()
...@@ -52,7 +52,7 @@ class RelationsTest extends TestCase ...@@ -52,7 +52,7 @@ class RelationsTest extends TestCase
$this->assertEquals('John Doe', $owner->name); $this->assertEquals('John Doe', $owner->name);
$book = Book::create(['title' => 'A Clash of Kings']); $book = Book::create(['title' => 'A Clash of Kings']);
$this->assertEquals(null, $book->author); $this->assertNull($book->author);
} }
public function testHasOne() public function testHasOne()
...@@ -91,8 +91,8 @@ class RelationsTest extends TestCase ...@@ -91,8 +91,8 @@ class RelationsTest extends TestCase
$user = $items[0]->getRelation('user'); $user = $items[0]->getRelation('user');
$this->assertInstanceOf('User', $user); $this->assertInstanceOf('User', $user);
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(1, count($items[0]->getRelations())); $this->assertCount(1, $items[0]->getRelations());
$this->assertEquals(null, $items[3]->getRelation('user')); $this->assertNull($items[3]->getRelation('user'));
} }
public function testWithHashMany() public function testWithHashMany()
...@@ -106,7 +106,7 @@ class RelationsTest extends TestCase ...@@ -106,7 +106,7 @@ class RelationsTest extends TestCase
$user = User::with('items')->find($user->_id); $user = User::with('items')->find($user->_id);
$items = $user->getRelation('items'); $items = $user->getRelation('items');
$this->assertEquals(3, count($items)); $this->assertCount(3, $items);
$this->assertInstanceOf('Item', $items[0]); $this->assertInstanceOf('Item', $items[0]);
} }
...@@ -132,7 +132,7 @@ class RelationsTest extends TestCase ...@@ -132,7 +132,7 @@ class RelationsTest extends TestCase
$user = User::find($user->_id); $user = User::find($user->_id);
$items = $user->items; $items = $user->items;
$this->assertEquals(1, count($items)); $this->assertCount(1, $items);
$this->assertInstanceOf('Item', $items[0]); $this->assertInstanceOf('Item', $items[0]);
$this->assertEquals($user->_id, $items[0]->user_id); $this->assertEquals($user->_id, $items[0]->user_id);
...@@ -161,8 +161,8 @@ class RelationsTest extends TestCase ...@@ -161,8 +161,8 @@ class RelationsTest extends TestCase
$client = Client::with('users')->first(); $client = Client::with('users')->first();
// Check for relation attributes // Check for relation attributes
$this->assertTrue(array_key_exists('user_ids', $client->getAttributes())); $this->assertArrayHasKey('user_ids', $client->getAttributes());
$this->assertTrue(array_key_exists('client_ids', $user->getAttributes())); $this->assertArrayHasKey('client_ids', $user->getAttributes());
$clients = $user->getRelation('clients'); $clients = $user->getRelation('clients');
$users = $client->getRelation('users'); $users = $client->getRelation('users');
...@@ -190,8 +190,8 @@ class RelationsTest extends TestCase ...@@ -190,8 +190,8 @@ class RelationsTest extends TestCase
$this->assertInstanceOf('User', $user); $this->assertInstanceOf('User', $user);
// Assert they are not attached // Assert they are not attached
$this->assertFalse(in_array($client->_id, $user->client_ids)); $this->assertNotContains($client->_id, $user->client_ids);
$this->assertFalse(in_array($user->_id, $client->user_ids)); $this->assertNotContains($user->_id, $client->user_ids);
$this->assertCount(1, $user->clients); $this->assertCount(1, $user->clients);
$this->assertCount(1, $client->users); $this->assertCount(1, $client->users);
...@@ -203,8 +203,8 @@ class RelationsTest extends TestCase ...@@ -203,8 +203,8 @@ class RelationsTest extends TestCase
$client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first();
// Assert they are attached // Assert they are attached
$this->assertTrue(in_array($client->_id, $user->client_ids)); $this->assertContains($client->_id, $user->client_ids);
$this->assertTrue(in_array($user->_id, $client->user_ids)); $this->assertContains($user->_id, $client->user_ids);
$this->assertCount(2, $user->clients); $this->assertCount(2, $user->clients);
$this->assertCount(2, $client->users); $this->assertCount(2, $client->users);
...@@ -216,8 +216,8 @@ class RelationsTest extends TestCase ...@@ -216,8 +216,8 @@ class RelationsTest extends TestCase
$client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first();
// Assert they are not attached // Assert they are not attached
$this->assertFalse(in_array($client->_id, $user->client_ids)); $this->assertNotContains($client->_id, $user->client_ids);
$this->assertFalse(in_array($user->_id, $client->user_ids)); $this->assertNotContains($user->_id, $client->user_ids);
$this->assertCount(0, $user->clients); $this->assertCount(0, $user->clients);
$this->assertCount(1, $client->users); $this->assertCount(1, $client->users);
} }
...@@ -242,7 +242,7 @@ class RelationsTest extends TestCase ...@@ -242,7 +242,7 @@ class RelationsTest extends TestCase
$user = User::with('clients')->find($user->_id); $user = User::with('clients')->find($user->_id);
// Assert non attached ID's are detached succesfully // Assert non attached ID's are detached succesfully
$this->assertFalse(in_array('1234523', $user->client_ids)); $this->assertNotContains('1234523', $user->client_ids);
// Assert there are two client objects in the relationship // Assert there are two client objects in the relationship
$this->assertCount(2, $user->clients); $this->assertCount(2, $user->clients);
...@@ -330,12 +330,12 @@ class RelationsTest extends TestCase ...@@ -330,12 +330,12 @@ class RelationsTest extends TestCase
$group = Group::find($group->_id); $group = Group::find($group->_id);
// Check for custom relation attributes // Check for custom relation attributes
$this->assertTrue(array_key_exists('users', $group->getAttributes())); $this->assertArrayHasKey('users', $group->getAttributes());
$this->assertTrue(array_key_exists('groups', $user->getAttributes())); $this->assertArrayHasKey('groups', $user->getAttributes());
// Assert they are attached // Assert they are attached
$this->assertTrue(in_array($group->_id, $user->groups->pluck('_id')->toArray())); $this->assertContains($group->_id, $user->groups->pluck('_id')->toArray());
$this->assertTrue(in_array($user->_id, $group->users->pluck('_id')->toArray())); $this->assertContains($user->_id, $group->users->pluck('_id')->toArray());
$this->assertEquals($group->_id, $user->groups()->first()->_id); $this->assertEquals($group->_id, $user->groups()->first()->_id);
$this->assertEquals($user->_id, $group->users()->first()->_id); $this->assertEquals($user->_id, $group->users()->first()->_id);
} }
...@@ -370,16 +370,16 @@ class RelationsTest extends TestCase ...@@ -370,16 +370,16 @@ class RelationsTest extends TestCase
$user = User::with('photos')->find($user->_id); $user = User::with('photos')->find($user->_id);
$relations = $user->getRelations(); $relations = $user->getRelations();
$this->assertTrue(array_key_exists('photos', $relations)); $this->assertArrayHasKey('photos', $relations);
$this->assertEquals(1, $relations['photos']->count()); $this->assertEquals(1, $relations['photos']->count());
$photos = Photo::with('imageable')->get(); $photos = Photo::with('imageable')->get();
$relations = $photos[0]->getRelations(); $relations = $photos[0]->getRelations();
$this->assertTrue(array_key_exists('imageable', $relations)); $this->assertArrayHasKey('imageable', $relations);
$this->assertInstanceOf('User', $photos[0]->imageable); $this->assertInstanceOf('User', $photos[0]->imageable);
$relations = $photos[1]->getRelations(); $relations = $photos[1]->getRelations();
$this->assertTrue(array_key_exists('imageable', $relations)); $this->assertArrayHasKey('imageable', $relations);
$this->assertInstanceOf('Client', $photos[1]->imageable); $this->assertInstanceOf('Client', $photos[1]->imageable);
} }
......
...@@ -7,15 +7,15 @@ return [ ...@@ -7,15 +7,15 @@ return [
'mongodb' => [ 'mongodb' => [
'name' => 'mongodb', 'name' => 'mongodb',
'driver' => 'mongodb', 'driver' => 'mongodb',
'host' => '127.0.0.1', 'host' => 'mongodb',
'database' => 'unittest', 'database' => 'unittest',
], ],
'mysql' => [ 'mysql' => [
'driver' => 'mysql', 'driver' => 'mysql',
'host' => '127.0.0.1', 'host' => 'mysql',
'database' => 'unittest', 'database' => 'unittest',
'username' => 'travis', 'username' => 'root',
'password' => '', 'password' => '',
'charset' => 'utf8', 'charset' => 'utf8',
'collation' => 'utf8_unicode_ci', 'collation' => 'utf8_unicode_ci',
......
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Address extends Eloquent class Address extends Eloquent
{ {
protected $connection = 'mongodb';
protected static $unguarded = true; protected static $unguarded = true;
public function addresses() public function addresses()
......
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Book extends Eloquent class Book extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'books'; protected $collection = 'books';
protected static $unguarded = true; protected static $unguarded = true;
protected $primaryKey = 'title'; protected $primaryKey = 'title';
......
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Client extends Eloquent class Client extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'clients'; protected $collection = 'clients';
protected static $unguarded = true; protected static $unguarded = true;
......
...@@ -4,11 +4,12 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,11 +4,12 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Group extends Eloquent class Group extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'groups'; protected $collection = 'groups';
protected static $unguarded = true; protected static $unguarded = true;
public function users() public function users()
{ {
return $this->belongsToMany('User', null, 'groups', 'users'); return $this->belongsToMany('User', 'users', 'groups', 'users', '_id', '_id', 'users');
} }
} }
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Item extends Eloquent class Item extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'items'; protected $collection = 'items';
protected static $unguarded = true; protected static $unguarded = true;
......
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Location extends Eloquent class Location extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'locations'; protected $collection = 'locations';
protected static $unguarded = true; protected static $unguarded = true;
} }
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Photo extends Eloquent class Photo extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'photos'; protected $collection = 'photos';
protected static $unguarded = true; protected static $unguarded = true;
......
...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent; ...@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Role extends Eloquent class Role extends Eloquent
{ {
protected $connection = 'mongodb';
protected $collection = 'roles'; protected $collection = 'roles';
protected static $unguarded = true; protected static $unguarded = true;
......
...@@ -7,6 +7,7 @@ class Soft extends Eloquent ...@@ -7,6 +7,7 @@ class Soft extends Eloquent
{ {
use SoftDeletes; use SoftDeletes;
protected $connection = 'mongodb';
protected $collection = 'soft'; protected $collection = 'soft';
protected static $unguarded = true; protected static $unguarded = true;
protected $dates = ['deleted_at']; protected $dates = ['deleted_at'];
......
<?php <?php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
...@@ -8,8 +9,9 @@ use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; ...@@ -8,8 +9,9 @@ use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
{ {
use Authenticatable, CanResetPassword; use Authenticatable, CanResetPassword, HybridRelations;
protected $connection = 'mongodb';
protected $dates = ['birthday', 'entry.date']; protected $dates = ['birthday', 'entry.date'];
protected static $unguarded = true; protected static $unguarded = true;
...@@ -45,7 +47,7 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword ...@@ -45,7 +47,7 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword
public function groups() public function groups()
{ {
return $this->belongsToMany('Group', null, 'users', 'groups'); return $this->belongsToMany('Group', 'groups', 'users', 'groups', '_id', '_id', 'groups');
} }
public function photos() public function photos()
......
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