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
php:
- 5.6
- 7
- 7.1
......
......@@ -41,6 +41,7 @@ composer require jenssegers/mongodb
5.2.x | 2.3.x or 3.0.x
5.3.x | 3.1.x or 3.2.x
5.4.x | 3.2.x
5.5.x | 3.3.x
And add the service provider in `config/app.php`:
......@@ -102,6 +103,15 @@ Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rathe
$books = $user->books()->sortBy('title');
```
Testing
-------
To run the test for this package, run:
```
docker-compose up
```
Configuration
-------------
......@@ -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
--------
......@@ -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:
```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:
......
......@@ -11,17 +11,18 @@
],
"license" : "MIT",
"require": {
"illuminate/support": "^5.1",
"illuminate/container": "^5.1",
"illuminate/database": "^5.1",
"illuminate/events": "^5.1",
"illuminate/support": "^5.5",
"illuminate/container": "^5.5",
"illuminate/database": "^5.5",
"illuminate/events": "^5.5",
"mongodb/mongodb": "^1.0.0"
},
"require-dev": {
"phpunit/phpunit": "^5.0|^6.0",
"phpunit/phpunit": "^6.0",
"orchestra/testbench": "^3.1",
"mockery/mockery": "^0.9",
"satooshi/php-coveralls": "^1.0"
"mockery/mockery": "^1.0",
"satooshi/php-coveralls": "^2.0",
"doctrine/dbal": "^2.5"
},
"autoload": {
"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
$date = $token['created_at']->toDateTime();
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$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->setTimezone(new DateTimeZone(date_default_timezone_get()));
$token['created_at'] = $date->format('Y-m-d H:i:s');
......
......@@ -8,7 +8,7 @@ use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Jenssegers\Mongodb\Eloquent\Model as Model;
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model implements
AuthenticatableContract,
......
......@@ -3,6 +3,8 @@
namespace Jenssegers\Mongodb;
use Illuminate\Database\Connection as BaseConnection;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use MongoDB\Client;
class Connection extends BaseConnection
......@@ -34,7 +36,7 @@ class Connection extends BaseConnection
$dsn = $this->getDsn($config);
// You can pass options directly to the MongoDB constructor
$options = array_get($config, 'options', []);
$options = Arr::get($config, 'options', []);
// Create the connection
$this->connection = $this->createConnection($dsn, $config, $options);
......@@ -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
* @return string
*/
protected function getDsn(array $config)
protected function getDsnString(array $config)
{
// Check if the user passed a complete dsn to the configuration.
if (!empty($config['dsn'])) {
return $config['dsn'];
$dsn_string = $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
$hosts = is_array($config['host']) ? $config['host'] : [$config['host']];
......@@ -177,6 +204,19 @@ class Connection extends BaseConnection
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
*/
......
......@@ -143,6 +143,14 @@ class Builder extends EloquentBuilder
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
*/
......@@ -162,10 +170,18 @@ class Builder extends EloquentBuilder
return $this->model->newFromBuilder((array) $results);
} // 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 $results;
}
/**
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->query->getConnection();
}
}
......@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb\Eloquent;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Relations\EmbedsMany;
use Jenssegers\Mongodb\Relations\EmbedsOne;
......@@ -32,7 +33,7 @@ trait EmbedsRelations
}
if (is_null($foreignKey)) {
$foreignKey = snake_case(class_basename($this));
$foreignKey = Str::snake(class_basename($this));
}
$query = $this->newQuery();
......@@ -67,7 +68,7 @@ trait EmbedsRelations
}
if (is_null($foreignKey)) {
$foreignKey = snake_case(class_basename($this));
$foreignKey = Str::snake(class_basename($this));
}
$query = $this->newQuery();
......
......@@ -214,11 +214,20 @@ trait HybridRelations
* @param string $collection
* @param string $foreignKey
* @param string $otherKey
* @param string $parentKey
* @param string $relatedKey
* @param string $relation
* @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
// 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.
......@@ -228,7 +237,15 @@ trait HybridRelations
// Check if it is a relation with an original model.
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
......@@ -252,7 +269,16 @@ trait HybridRelations
// appropriate query constraint and entirely manages the hydrations.
$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
*/
public function newEloquentBuilder($query)
{
if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) {
return new Builder($query);
} else {
return new EloquentBuilder($query);
}
}
}
......@@ -6,6 +6,7 @@ use Carbon\Carbon;
use DateTime;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\ObjectID;
......@@ -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.
// 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'];
}
......@@ -131,12 +132,12 @@ abstract class Model extends BaseModel
}
// 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);
}
// 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);
}
......@@ -149,8 +150,8 @@ abstract class Model extends BaseModel
protected function getAttributeFromArray($key)
{
// Support keys in dot notation.
if (str_contains($key, '.')) {
return array_get($this->attributes, $key);
if (Str::contains($key, '.')) {
return Arr::get($this->attributes, $key);
}
return parent::getAttributeFromArray($key);
......@@ -162,17 +163,17 @@ abstract class Model extends BaseModel
public function setAttribute($key, $value)
{
// Convert _id to ObjectID.
if ($key == '_id' and is_string($value)) {
if ($key == '_id' && is_string($value)) {
$builder = $this->newBaseQueryBuilder();
$value = $builder->convertKey($value);
} // Support keys in dot notation.
elseif (str_contains($key, '.')) {
elseif (Str::contains($key, '.')) {
if (in_array($key, $this->getDates()) && $value) {
$value = $this->fromDateTime($value);
}
array_set($this->attributes, $key, $value);
Arr::set($this->attributes, $key, $value);
return;
}
......@@ -199,8 +200,8 @@ abstract class Model extends BaseModel
// Convert dot-notation dates.
foreach ($this->getDates() as $key) {
if (str_contains($key, '.') and array_has($attributes, $key)) {
array_set($attributes, $key, (string) $this->asDateTime(array_get($attributes, $key)));
if (Str::contains($key, '.') && Arr::has($attributes, $key)) {
Arr::set($attributes, $key, (string) $this->asDateTime(Arr::get($attributes, $key)));
}
}
......@@ -218,20 +219,36 @@ abstract class Model extends BaseModel
/**
* @inheritdoc
*/
protected function originalIsNumericallyEquivalent($key)
protected function originalIsEquivalent($key, $current)
{
$current = $this->attributes[$key];
$original = $this->original[$key];
if (!array_key_exists($key, $this->original)) {
return false;
}
$original = $this->getOriginal($key);
if ($current === $original) {
return true;
}
if (null === $current) {
return false;
}
// Date comparison.
if (in_array($key, $this->getDates())) {
if ($this->isDateAttribute($key)) {
$current = $current instanceof UTCDateTime ? $this->asDateTime($current) : $current;
$original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $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
*/
public function drop($columns)
{
if (!is_array($columns)) {
$columns = [$columns];
}
$columns = Arr::wrap($columns);
// Unset attributes
foreach ($columns as $column) {
......@@ -263,16 +278,14 @@ abstract class Model extends BaseModel
if ($parameters = func_get_args()) {
$unique = false;
if (count($parameters) == 3) {
if (count($parameters) === 3) {
list($column, $values, $unique) = $parameters;
} else {
list($column, $values) = $parameters;
}
// Do batch push by default.
if (!is_array($values)) {
$values = [$values];
}
$values = Arr::wrap($values);
$query = $this->setKeysForSaveQuery($this->newQuery());
......@@ -294,9 +307,7 @@ abstract class Model extends BaseModel
public function pull($column, $values)
{
// Do batch pull by default.
if (!is_array($values)) {
$values = [$values];
}
$values = Arr::wrap($values);
$query = $this->setKeysForSaveQuery($this->newQuery());
......@@ -318,11 +329,11 @@ abstract class Model extends BaseModel
foreach ($values as $value) {
// 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;
}
array_push($current, $value);
$current[] = $value;
}
$this->attributes[$column] = $current;
......@@ -340,6 +351,7 @@ abstract class Model extends BaseModel
{
$current = $this->getAttributeFromArray($column) ?: [];
if (is_array($current)) {
foreach ($values as $value) {
$keys = array_keys($current, $value);
......@@ -347,6 +359,7 @@ abstract class Model extends BaseModel
unset($current[$key]);
}
}
}
$this->attributes[$column] = array_values($current);
......
......@@ -8,6 +8,7 @@ use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Connection;
use MongoCollection;
use MongoDB\BSON\ObjectID;
......@@ -232,7 +233,7 @@ class Builder extends BaseBuilder
$wheres = $this->compileWheres();
// 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 = [];
$unwinds = [];
......@@ -286,7 +287,7 @@ class Builder extends BaseBuilder
}
// The _id field is mandatory when using grouping.
if ($group and empty($group['_id'])) {
if ($group && empty($group['_id'])) {
$group['_id'] = null;
}
......@@ -490,6 +491,24 @@ class Builder extends BaseBuilder
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
*/
......@@ -563,7 +582,7 @@ class Builder extends BaseBuilder
public function update(array $values, array $options = [])
{
// Use $set as default operator.
if (!starts_with(key($values), '$')) {
if (!Str::startsWith(key($values), '$')) {
$values = ['$set' => $values];
}
......@@ -599,6 +618,28 @@ class Builder extends BaseBuilder
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
*/
......@@ -705,7 +746,7 @@ class Builder extends BaseBuilder
$operator = $unique ? '$addToSet' : '$push';
// 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)) {
$query = [$operator => $column];
......@@ -728,7 +769,7 @@ class Builder extends BaseBuilder
public function pull($column, $value = null)
{
// 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.
$operator = $batch ? '$pullAll' : '$pull';
......@@ -804,7 +845,7 @@ class Builder extends BaseBuilder
*/
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);
}
......@@ -822,7 +863,7 @@ class Builder extends BaseBuilder
if (func_num_args() == 3) {
$operator = &$params[1];
if (starts_with($operator, '$')) {
if (Str::startsWith($operator, '$')) {
$operator = substr($operator, 1);
}
}
......@@ -866,7 +907,7 @@ class Builder extends BaseBuilder
}
// 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.
if (isset($where['values'])) {
foreach ($where['values'] as &$value) {
......@@ -891,12 +932,18 @@ class Builder extends BaseBuilder
$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
// first item. So if we see that there are multiple wheres, we will
// 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'];
}
......@@ -922,6 +969,17 @@ class Builder extends BaseBuilder
return $compiled;
}
/**
* @param array $where
* @return array
*/
protected function compileWhereAll(array $where)
{
extract($where);
return [$column => ['$all' => array_values($values)]];
}
/**
* @param array $where
* @return array
......@@ -938,10 +996,10 @@ class Builder extends BaseBuilder
$regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value));
// Convert like to regular expression.
if (!starts_with($value, '%')) {
if (!Str::startsWith($value, '%')) {
$regex = '^' . $regex;
}
if (!ends_with($value, '%')) {
if (!Str::endsWith($value, '%')) {
$regex = $regex . '$';
}
......@@ -958,12 +1016,12 @@ class Builder extends BaseBuilder
// For inverse regexp operations, we can just use the $not operator
// and pass it a Regex instence.
if (starts_with($operator, 'not')) {
if (Str::startsWith($operator, 'not')) {
$operator = 'not';
}
}
if (!isset($operator) or $operator == '=') {
if (!isset($operator) || $operator == '=') {
$query = [$column => $value];
} elseif (array_key_exists($operator, $this->conversion)) {
$query = [$column => [$this->conversion[$operator] => $value]];
......
......@@ -117,7 +117,7 @@ class MongoQueue extends DatabaseQueue
})->get();
foreach ($reserved as $job) {
$attempts = $job['attempts'] + 1;
$attempts = $job['attempts'];
$this->releaseJob($job['_id'], $attempts);
}
}
......
......@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany;
use Illuminate\Support\Arr;
class BelongsToMany extends EloquentBelongsToMany
{
......@@ -93,7 +94,7 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* @inheritdoc
*/
public function create(array $attributes, array $joining = [], $touch = true)
public function create(array $attributes = [], array $joining = [], $touch = true)
{
$instance = $this->related->newInstance($attributes);
......@@ -134,6 +135,8 @@ class BelongsToMany extends EloquentBelongsToMany
$records = $this->formatSyncList($ids);
$current = Arr::wrap($current);
$detach = array_diff($current, array_keys($records));
// We need to make sure we pass a clean array, so that it is not interpreted
......@@ -143,7 +146,7 @@ class BelongsToMany extends EloquentBelongsToMany
// 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
// 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);
$changes['detached'] = (array) array_map(function ($v) {
......@@ -184,7 +187,7 @@ class BelongsToMany extends EloquentBelongsToMany
$id = $model->getKey();
// 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 {
if ($id instanceof Collection) {
$id = $id->modelKeys();
......@@ -195,7 +198,7 @@ class BelongsToMany extends EloquentBelongsToMany
$query->whereIn($this->related->getKeyName(), (array) $id);
// 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.
......@@ -231,7 +234,7 @@ class BelongsToMany extends EloquentBelongsToMany
}
// Remove the relation to the parent.
$query->pull($this->foreignKey, $this->parent->getKey());
$query->pull($this->foreignPivotKey, $this->parent->getKey());
if ($touch) {
$this->touchIfTouching();
......@@ -245,7 +248,7 @@ class BelongsToMany extends EloquentBelongsToMany
*/
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
// of the relation so that we will easily and quickly match them to their
......@@ -286,15 +289,23 @@ class BelongsToMany extends EloquentBelongsToMany
*/
public function getForeignKey()
{
return $this->foreignKey;
return $this->foreignPivotKey;
}
/**
* @inheritdoc
*/
public function getQualifiedForeignPivotKeyName()
{
return $this->foreignPivotKey;
}
/**
* @inheritdoc
*/
public function getQualifiedForeignKeyName()
public function getQualifiedRelatedPivotKeyName()
{
return $this->foreignKey;
return $this->relatedPivotKey;
}
/**
......@@ -324,6 +335,6 @@ class BelongsToMany extends EloquentBelongsToMany
*/
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;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Arr;
use MongoDB\BSON\ObjectID;
class EmbedsMany extends EmbedsOneOrMany
......@@ -39,7 +40,7 @@ class EmbedsMany extends EmbedsOneOrMany
public function performInsert(Model $model)
{
// Generate a new key if needed.
if ($model->getKeyName() == '_id' and !$model->getKey()) {
if ($model->getKeyName() == '_id' && !$model->getKey()) {
$model->setAttribute('_id', new ObjectID);
}
......@@ -79,7 +80,7 @@ class EmbedsMany extends EmbedsOneOrMany
$foreignKey = $this->getForeignKeyValue($model);
// 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.
$result = $this->getBaseQuery()->where($this->localKey . '.' . $model->getKeyName(), $foreignKey)
......
......@@ -3,6 +3,7 @@
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use MongoDB\BSON\ObjectID;
class EmbedsOne extends EmbedsOneOrMany
......@@ -36,7 +37,7 @@ class EmbedsOne extends EmbedsOneOrMany
public function performInsert(Model $model)
{
// Generate a new key if needed.
if ($model->getKeyName() == '_id' and !$model->getKey()) {
if ($model->getKeyName() == '_id' && !$model->getKey()) {
$model->setAttribute('_id', new ObjectID);
}
......@@ -71,7 +72,7 @@ class EmbedsOne extends EmbedsOneOrMany
}
// 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);
......
......@@ -94,9 +94,11 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Shorthand to get the results of the relationship.
*
* @param array $columns
*
* @return Collection
*/
public function get()
public function get($columns = ['*'])
{
return $this->getResults();
}
......@@ -265,7 +267,7 @@ abstract class EmbedsOneOrMany extends Relation
$models = $this->eagerLoadRelations($models);
}
return new Collection($models);
return $this->related->newCollection($models);
}
/**
......@@ -280,7 +282,12 @@ abstract class EmbedsOneOrMany extends Relation
return;
}
$model = $this->related->newFromBuilder((array) $attributes);
$connection = $this->related->getConnection();
$model = $this->related->newFromBuilder(
(array) $attributes,
$connection ? $connection->getName() : null
);
$model->setParentRelation($this);
......
......@@ -156,7 +156,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
*/
public function geospatial($columns = null, $index = '2d', $options = [])
{
if ($index == '2d' or $index == '2dsphere') {
if ($index == '2d' || $index == '2dsphere') {
$columns = $this->fluent($columns);
$columns = array_flip($columns);
......
......@@ -106,6 +106,16 @@ class Builder extends \Illuminate\Database\Schema\Builder
return $blueprint->drop();
}
/**
* @inheritdoc
*/
public function dropAllTables()
{
foreach ($this->getAllCollections() as $collection) {
$this->drop($collection);
}
}
/**
* @inheritdoc
*/
......@@ -113,4 +123,19 @@ class Builder extends \Illuminate\Database\Schema\Builder
{
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
// public function testDynamic()
// {
// $dbs = DB::connection('mongodb')->listCollections();
// $this->assertTrue(is_array($dbs));
// $this->assertInternalType('array', $dbs);
// }
// public function testMultipleConnections()
......@@ -59,29 +59,29 @@ class ConnectionTest extends TestCase
// $mongoclient = $connection->getMongoClient();
// $hosts = $mongoclient->getHosts();
// $this->assertEquals(1, count($hosts));
// $this->assertCount(1, $hosts);
// }
public function testQueryLog()
{
DB::enableQueryLog();
$this->assertEquals(0, count(DB::getQueryLog()));
$this->assertCount(0, DB::getQueryLog());
DB::collection('items')->get();
$this->assertEquals(1, count(DB::getQueryLog()));
$this->assertCount(1, DB::getQueryLog());
DB::collection('items')->insert(['name' => 'test']);
$this->assertEquals(2, count(DB::getQueryLog()));
$this->assertCount(2, DB::getQueryLog());
DB::collection('items')->count();
$this->assertEquals(3, count(DB::getQueryLog()));
$this->assertCount(3, DB::getQueryLog());
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();
$this->assertEquals(5, count(DB::getQueryLog()));
$this->assertCount(5, DB::getQueryLog());
}
public function testSchemaBuilder()
......@@ -98,12 +98,13 @@ class ConnectionTest extends TestCase
public function testAuth()
{
$host = Config::get('database.connections.mongodb.host');
Config::set('database.connections.mongodb.username', 'foo');
Config::set('database.connections.mongodb.password', 'bar');
Config::set('database.connections.mongodb.options.database', 'custom');
$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()
......
This diff is collapsed.
......@@ -27,13 +27,13 @@ class HybridRelationsTest extends TestCase
// Mysql User
$user->name = "John Doe";
$user->save();
$this->assertTrue(is_int($user->id));
$this->assertInternalType('int', $user->id);
// SQL has many
$book = new Book(['title' => 'Game of Thrones']);
$user->books()->save($book);
$user = MysqlUser::find($user->id); // refetch
$this->assertEquals(1, count($user->books));
$this->assertCount(1, $user->books);
// MongoDB belongs to
$book = $user->books()->first(); // refetch
......@@ -58,7 +58,7 @@ class HybridRelationsTest extends TestCase
$book = new MysqlBook(['title' => 'Game of Thrones']);
$user->mysqlBooks()->save($book);
$user = User::find($user->_id); // refetch
$this->assertEquals(1, count($user->mysqlBooks));
$this->assertCount(1, $user->mysqlBooks);
// SQL belongs to
$book = $user->mysqlBooks()->first(); // refetch
......@@ -93,8 +93,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3;
$otherUser->save();
// Make sure they are created
$this->assertTrue(is_int($user->id));
$this->assertTrue(is_int($otherUser->id));
$this->assertInternalType('int', $user->id);
$this->assertInternalType('int', $otherUser->id);
// Clear to start
$user->books()->truncate();
$otherUser->books()->truncate();
......@@ -147,8 +147,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3;
$otherUser->save();
// Make sure they are created
$this->assertTrue(is_int($user->id));
$this->assertTrue(is_int($otherUser->id));
$this->assertInternalType('int', $user->id);
$this->assertInternalType('int', $otherUser->id);
// Clear to start
Book::truncate();
MysqlBook::truncate();
......
......@@ -21,7 +21,7 @@ class ModelTest extends TestCase
$user = new User;
$this->assertInstanceOf(Model::class, $user);
$this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection());
$this->assertEquals(false, $user->exists);
$this->assertFalse($user->exists);
$this->assertEquals('users', $user->getTable());
$this->assertEquals('_id', $user->getKeyName());
}
......@@ -35,11 +35,11 @@ class ModelTest extends TestCase
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals(1, User::count());
$this->assertTrue(isset($user->_id));
$this->assertTrue(is_string($user->_id));
$this->assertInternalType('string', $user->_id);
$this->assertNotEquals('', (string) $user->_id);
$this->assertNotEquals(0, strlen((string) $user->_id));
$this->assertInstanceOf(Carbon::class, $user->created_at);
......@@ -67,7 +67,7 @@ class ModelTest extends TestCase
$check->age = 36;
$check->save();
$this->assertEquals(true, $check->exists);
$this->assertTrue($check->exists);
$this->assertInstanceOf(Carbon::class, $check->created_at);
$this->assertInstanceOf(Carbon::class, $check->updated_at);
$this->assertEquals(1, User::count());
......@@ -93,7 +93,7 @@ class ModelTest extends TestCase
$user->age = 35;
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id);
$raw = $user->getAttributes();
......@@ -106,7 +106,7 @@ class ModelTest extends TestCase
$user->age = 35;
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals('customId', $user->_id);
$raw = $user->getAttributes();
......@@ -122,7 +122,7 @@ class ModelTest extends TestCase
$user->age = 35;
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals(1, $user->_id);
$raw = $user->getAttributes();
......@@ -137,7 +137,7 @@ class ModelTest extends TestCase
$user->age = 35;
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals(1, User::count());
$user->delete();
......@@ -161,7 +161,7 @@ class ModelTest extends TestCase
$all = User::all();
$this->assertEquals(2, count($all));
$this->assertCount(2, $all);
$this->assertContains('John Doe', $all->pluck('name'));
$this->assertContains('Jane Doe', $all->pluck('name'));
}
......@@ -177,7 +177,7 @@ class ModelTest extends TestCase
$check = User::find($user->_id);
$this->assertInstanceOf(Model::class, $check);
$this->assertEquals(true, $check->exists);
$this->assertTrue($check->exists);
$this->assertEquals($user->_id, $check->_id);
$this->assertEquals('John Doe', $check->name);
......@@ -192,7 +192,7 @@ class ModelTest extends TestCase
]);
$users = User::get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$this->assertInstanceOf(Collection::class, $users);
$this->assertInstanceOf(Model::class, $users[0]);
}
......@@ -216,10 +216,10 @@ class ModelTest extends TestCase
$this->assertEquals(0, $items->count());
$item = Item::where('name', 'nothing')->first();
$this->assertEquals(null, $item);
$this->assertNull($item);
$item = Item::find('51c33d8981fec6813e00000a');
$this->assertEquals(null, $item);
$this->assertNull($item);
}
public function testFindOrfail()
......@@ -233,7 +233,7 @@ class ModelTest extends TestCase
$user = User::create(['name' => 'Jane Poe']);
$this->assertInstanceOf(Model::class, $user);
$this->assertEquals(true, $user->exists);
$this->assertTrue($user->exists);
$this->assertEquals('Jane Poe', $user->name);
$check = User::where('name', 'Jane Poe')->first();
......@@ -278,12 +278,12 @@ class ModelTest extends TestCase
$this->assertEquals(2, Soft::count());
$user = Soft::where('name', 'John Doe')->first();
$this->assertEquals(true, $user->exists);
$this->assertEquals(false, $user->trashed());
$this->assertTrue($user->exists);
$this->assertFalse($user->trashed());
$this->assertNull($user->deleted_at);
$user->delete();
$this->assertEquals(true, $user->trashed());
$this->assertTrue($user->trashed());
$this->assertNotNull($user->deleted_at);
$user = Soft::where('name', 'John Doe')->first();
......@@ -295,7 +295,7 @@ class ModelTest extends TestCase
$user = Soft::withTrashed()->where('name', 'John Doe')->first();
$this->assertNotNull($user);
$this->assertInstanceOf(Carbon::class, $user->deleted_at);
$this->assertEquals(true, $user->trashed());
$this->assertTrue($user->trashed());
$user->restore();
$this->assertEquals(2, Soft::count());
......@@ -340,9 +340,9 @@ class ModelTest extends TestCase
$keys = array_keys($array);
sort($keys);
$this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys);
$this->assertTrue(is_string($array['created_at']));
$this->assertTrue(is_string($array['updated_at']));
$this->assertTrue(is_string($array['_id']));
$this->assertInternalType('string', $array['created_at']);
$this->assertInternalType('string', $array['updated_at']);
$this->assertInternalType('string', $array['_id']);
}
public function testUnset()
......@@ -352,7 +352,7 @@ class ModelTest extends TestCase
$user1->unset('note1');
$this->assertFalse(isset($user1->note1));
$this->assertObjectNotHasAttribute('note1', $user1);
$this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2));
......@@ -361,15 +361,15 @@ class ModelTest extends TestCase
$user1 = User::find($user1->_id);
$user2 = User::find($user2->_id);
$this->assertFalse(isset($user1->note1));
$this->assertObjectNotHasAttribute('note1', $user1);
$this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2));
$user2->unset(['note1', 'note2']);
$this->assertFalse(isset($user2->note1));
$this->assertFalse(isset($user2->note2));
$this->assertObjectNotHasAttribute('note1', $user2);
$this->assertObjectNotHasAttribute('note2', $user2);
}
public function testDates()
......@@ -396,7 +396,7 @@ class ModelTest extends TestCase
$this->assertEquals($item->getOriginal('created_at')
->toDateTime()
->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
$item = Item::create(['name' => 'sword']);
......@@ -534,4 +534,18 @@ class ModelTest extends TestCase
$user->birthday = new DateTime('19 august 1989');
$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
public function testWhere()
{
$users = User::where('age', 35)->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
$users = User::where('age', '=', 35)->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
$users = User::where('age', '>=', 35)->get();
$this->assertEquals(4, count($users));
$this->assertCount(4, $users);
$users = User::where('age', '<=', 18)->get();
$this->assertEquals(1, count($users));
$this->assertCount(1, $users);
$users = User::where('age', '!=', 35)->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
$users = User::where('age', '<>', 35)->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
}
public function testAndWhere()
{
$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();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
}
public function testLike()
{
$users = User::where('name', 'like', '%doe')->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::where('name', 'like', '%y%')->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
$users = User::where('name', 'LIKE', '%y%')->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
$users = User::where('name', 'like', 't%')->get();
$this->assertEquals(1, count($users));
$this->assertCount(1, $users);
}
public function testSelect()
......@@ -74,75 +74,75 @@ class QueryTest extends TestCase
$user = User::where('name', 'John Doe')->select('name')->first();
$this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age);
$this->assertEquals(null, $user->title);
$this->assertNull($user->age);
$this->assertNull($user->title);
$user = User::where('name', 'John Doe')->select('name', 'title')->first();
$this->assertEquals('John Doe', $user->name);
$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();
$this->assertEquals('John Doe', $user->name);
$this->assertEquals('admin', $user->title);
$this->assertEquals(null, $user->age);
$this->assertNull($user->age);
$user = User::where('name', 'John Doe')->get(['name'])->first();
$this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age);
$this->assertNull($user->age);
}
public function testOrWhere()
{
$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();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
}
public function testBetween()
{
$users = User::whereBetween('age', [0, 25])->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::whereBetween('age', [13, 23])->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
// testing whereNotBetween for version 4.1
$users = User::whereBetween('age', [0, 25], 'and', true)->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
}
public function testIn()
{
$users = User::whereIn('age', [13, 23])->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::whereIn('age', [33, 35, 13])->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
$users = User::whereNotIn('age', [33, 35])->get();
$this->assertEquals(4, count($users));
$this->assertCount(4, $users);
$users = User::whereNotNull('age')
->whereNotIn('age', [33, 35])->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
}
public function testWhereNull()
{
$users = User::whereNull('age')->get();
$this->assertEquals(1, count($users));
$this->assertCount(1, $users);
}
public function testWhereNotNull()
{
$users = User::whereNotNull('age')->get();
$this->assertEquals(8, count($users));
$this->assertCount(8, $users);
}
public function testOrder()
......@@ -169,16 +169,16 @@ class QueryTest extends TestCase
public function testGroupBy()
{
$users = User::groupBy('title')->get();
$this->assertEquals(3, count($users));
$this->assertCount(3, $users);
$users = User::groupBy('age')->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
$users = User::groupBy('age')->skip(1)->get();
$this->assertEquals(5, count($users));
$this->assertCount(5, $users);
$users = User::groupBy('age')->take(2)->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::groupBy('age')->orderBy('age', 'desc')->get();
$this->assertEquals(37, $users[0]->age);
......@@ -186,13 +186,13 @@ class QueryTest extends TestCase
$this->assertEquals(33, $users[2]->age);
$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(33, $users[1]->age);
$this->assertNull($users[0]->name);
$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);
}
......@@ -220,7 +220,7 @@ class QueryTest extends TestCase
})
->get();
$this->assertEquals(5, count($users));
$this->assertCount(5, $users);
$users = User::where('title', 'user')->where(function ($query) {
$query->where('age', 35)
......@@ -228,7 +228,7 @@ class QueryTest extends TestCase
})
->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::where('age', 35)->orWhere(function ($query) {
$query->where('title', 'admin')
......@@ -236,7 +236,7 @@ class QueryTest extends TestCase
})
->get();
$this->assertEquals(5, count($users));
$this->assertCount(5, $users);
$users = User::whereNull('deleted_at')
->where('title', 'admin')
......@@ -266,13 +266,13 @@ class QueryTest extends TestCase
$where = ['age' => ['$gt' => 30, '$lt' => 40]];
$users = User::whereRaw($where)->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
$where1 = ['age' => ['$gt' => 30, '$lte' => 35]];
$where2 = ['age' => ['$gt' => 35, '$lt' => 40]];
$users = User::whereRaw($where1)->orWhereRaw($where2)->get();
$this->assertEquals(6, count($users));
$this->assertCount(6, $users);
}
public function testMultipleOr()
......@@ -284,7 +284,7 @@ class QueryTest extends TestCase
$query->where('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
$users = User::where(function ($query) {
$query->orWhere('age', 35)->orWhere('age', 33);
......@@ -293,7 +293,7 @@ class QueryTest extends TestCase
$query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get();
$this->assertEquals(2, count($users));
$this->assertCount(2, $users);
}
public function testPaginate()
......
......@@ -24,7 +24,7 @@ class RelationsTest extends TestCase
Book::create(['title' => 'A Clash of Kings', 'author_id' => $author->_id]);
$books = $author->books;
$this->assertEquals(2, count($books));
$this->assertCount(2, $books);
$user = User::create(['name' => 'John Doe']);
Item::create(['type' => 'knife', 'user_id' => $user->_id]);
......@@ -33,7 +33,7 @@ class RelationsTest extends TestCase
Item::create(['type' => 'bag', 'user_id' => null]);
$items = $user->items;
$this->assertEquals(3, count($items));
$this->assertCount(3, $items);
}
public function testBelongsTo()
......@@ -52,7 +52,7 @@ class RelationsTest extends TestCase
$this->assertEquals('John Doe', $owner->name);
$book = Book::create(['title' => 'A Clash of Kings']);
$this->assertEquals(null, $book->author);
$this->assertNull($book->author);
}
public function testHasOne()
......@@ -91,8 +91,8 @@ class RelationsTest extends TestCase
$user = $items[0]->getRelation('user');
$this->assertInstanceOf('User', $user);
$this->assertEquals('John Doe', $user->name);
$this->assertEquals(1, count($items[0]->getRelations()));
$this->assertEquals(null, $items[3]->getRelation('user'));
$this->assertCount(1, $items[0]->getRelations());
$this->assertNull($items[3]->getRelation('user'));
}
public function testWithHashMany()
......@@ -106,7 +106,7 @@ class RelationsTest extends TestCase
$user = User::with('items')->find($user->_id);
$items = $user->getRelation('items');
$this->assertEquals(3, count($items));
$this->assertCount(3, $items);
$this->assertInstanceOf('Item', $items[0]);
}
......@@ -132,7 +132,7 @@ class RelationsTest extends TestCase
$user = User::find($user->_id);
$items = $user->items;
$this->assertEquals(1, count($items));
$this->assertCount(1, $items);
$this->assertInstanceOf('Item', $items[0]);
$this->assertEquals($user->_id, $items[0]->user_id);
......@@ -161,8 +161,8 @@ class RelationsTest extends TestCase
$client = Client::with('users')->first();
// Check for relation attributes
$this->assertTrue(array_key_exists('user_ids', $client->getAttributes()));
$this->assertTrue(array_key_exists('client_ids', $user->getAttributes()));
$this->assertArrayHasKey('user_ids', $client->getAttributes());
$this->assertArrayHasKey('client_ids', $user->getAttributes());
$clients = $user->getRelation('clients');
$users = $client->getRelation('users');
......@@ -190,8 +190,8 @@ class RelationsTest extends TestCase
$this->assertInstanceOf('User', $user);
// Assert they are not attached
$this->assertFalse(in_array($client->_id, $user->client_ids));
$this->assertFalse(in_array($user->_id, $client->user_ids));
$this->assertNotContains($client->_id, $user->client_ids);
$this->assertNotContains($user->_id, $client->user_ids);
$this->assertCount(1, $user->clients);
$this->assertCount(1, $client->users);
......@@ -203,8 +203,8 @@ class RelationsTest extends TestCase
$client = Client::Where('name', '=', 'Buffet Bar Inc.')->first();
// Assert they are attached
$this->assertTrue(in_array($client->_id, $user->client_ids));
$this->assertTrue(in_array($user->_id, $client->user_ids));
$this->assertContains($client->_id, $user->client_ids);
$this->assertContains($user->_id, $client->user_ids);
$this->assertCount(2, $user->clients);
$this->assertCount(2, $client->users);
......@@ -216,8 +216,8 @@ class RelationsTest extends TestCase
$client = Client::Where('name', '=', 'Buffet Bar Inc.')->first();
// Assert they are not attached
$this->assertFalse(in_array($client->_id, $user->client_ids));
$this->assertFalse(in_array($user->_id, $client->user_ids));
$this->assertNotContains($client->_id, $user->client_ids);
$this->assertNotContains($user->_id, $client->user_ids);
$this->assertCount(0, $user->clients);
$this->assertCount(1, $client->users);
}
......@@ -242,7 +242,7 @@ class RelationsTest extends TestCase
$user = User::with('clients')->find($user->_id);
// 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
$this->assertCount(2, $user->clients);
......@@ -330,12 +330,12 @@ class RelationsTest extends TestCase
$group = Group::find($group->_id);
// Check for custom relation attributes
$this->assertTrue(array_key_exists('users', $group->getAttributes()));
$this->assertTrue(array_key_exists('groups', $user->getAttributes()));
$this->assertArrayHasKey('users', $group->getAttributes());
$this->assertArrayHasKey('groups', $user->getAttributes());
// Assert they are attached
$this->assertTrue(in_array($group->_id, $user->groups->pluck('_id')->toArray()));
$this->assertTrue(in_array($user->_id, $group->users->pluck('_id')->toArray()));
$this->assertContains($group->_id, $user->groups->pluck('_id')->toArray());
$this->assertContains($user->_id, $group->users->pluck('_id')->toArray());
$this->assertEquals($group->_id, $user->groups()->first()->_id);
$this->assertEquals($user->_id, $group->users()->first()->_id);
}
......@@ -370,16 +370,16 @@ class RelationsTest extends TestCase
$user = User::with('photos')->find($user->_id);
$relations = $user->getRelations();
$this->assertTrue(array_key_exists('photos', $relations));
$this->assertArrayHasKey('photos', $relations);
$this->assertEquals(1, $relations['photos']->count());
$photos = Photo::with('imageable')->get();
$relations = $photos[0]->getRelations();
$this->assertTrue(array_key_exists('imageable', $relations));
$this->assertArrayHasKey('imageable', $relations);
$this->assertInstanceOf('User', $photos[0]->imageable);
$relations = $photos[1]->getRelations();
$this->assertTrue(array_key_exists('imageable', $relations));
$this->assertArrayHasKey('imageable', $relations);
$this->assertInstanceOf('Client', $photos[1]->imageable);
}
......
......@@ -7,15 +7,15 @@ return [
'mongodb' => [
'name' => 'mongodb',
'driver' => 'mongodb',
'host' => '127.0.0.1',
'host' => 'mongodb',
'database' => 'unittest',
],
'mysql' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'host' => 'mysql',
'database' => 'unittest',
'username' => 'travis',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
......
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Address extends Eloquent
{
protected $connection = 'mongodb';
protected static $unguarded = true;
public function addresses()
......
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Book extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'books';
protected static $unguarded = true;
protected $primaryKey = 'title';
......
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Client extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'clients';
protected static $unguarded = true;
......
......@@ -4,11 +4,12 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Group extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'groups';
protected static $unguarded = true;
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;
class Item extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'items';
protected static $unguarded = true;
......
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Location extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'locations';
protected static $unguarded = true;
}
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Photo extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'photos';
protected static $unguarded = true;
......
......@@ -4,6 +4,7 @@ use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Role extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'roles';
protected static $unguarded = true;
......
......@@ -7,6 +7,7 @@ class Soft extends Eloquent
{
use SoftDeletes;
protected $connection = 'mongodb';
protected $collection = 'soft';
protected static $unguarded = true;
protected $dates = ['deleted_at'];
......
<?php
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
......@@ -8,8 +9,9 @@ use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
use Authenticatable, CanResetPassword, HybridRelations;
protected $connection = 'mongodb';
protected $dates = ['birthday', 'entry.date'];
protected static $unguarded = true;
......@@ -45,7 +47,7 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword
public function groups()
{
return $this->belongsToMany('Group', null, 'users', 'groups');
return $this->belongsToMany('Group', 'groups', 'users', 'groups', '_id', '_id', 'groups');
}
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