Skip to content

Commit 12e7cb2

Browse files
committed
Merge pull request #70 from DyeH/master
Many to Many relationships
2 parents 4d00587 + 0eed896 commit 12e7cb2

File tree

7 files changed

+674
-125
lines changed

7 files changed

+674
-125
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ phpunit.phar
44
composer.phar
55
composer.lock
66
*.sublime-project
7-
*.sublime-workspace
7+
*.sublime-workspace
8+
*.project

src/Jenssegers/Mongodb/Model.php

+39-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Jenssegers\Mongodb\DatabaseManager as Resolver;
88
use Jenssegers\Mongodb\Builder as QueryBuilder;
99
use Jenssegers\Mongodb\Relations\BelongsTo;
10+
use Jenssegers\Mongodb\Relations\BelongsToMany;
1011

1112
use Carbon\Carbon;
1213
use DateTime;
@@ -199,6 +200,43 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
199200
return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
200201
}
201202

203+
/**
204+
* Define a many-to-many relationship.
205+
*
206+
* @param string $related
207+
* @param string $table
208+
* @param string $foreignKey
209+
* @param string $otherKey
210+
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
211+
*/
212+
public function belongsToMany($related, $collection = null, $foreignKey = null, $otherKey = null)
213+
{
214+
$caller = $this->getBelongsToManyCaller();
215+
216+
// First, we'll need to determine the foreign key and "other key" for the
217+
// relationship. Once we have determined the keys we'll make the query
218+
// instances as well as the relationship instances we need for this.
219+
$foreignKey = $foreignKey ?: $this->getForeignKey() . 's';
220+
221+
$instance = new $related;
222+
223+
$otherKey = $otherKey ?: $instance->getForeignKey() . 's';
224+
// If no table name was provided, we can guess it by concatenating the two
225+
// models using underscores in alphabetical order. The two model names
226+
// are transformed to snake case from their default CamelCase also.
227+
if (is_null($collection))
228+
{
229+
$collection = snake_case(str_plural(class_basename($related)));
230+
}
231+
232+
// Now we're ready to create a new query builder for the related model and
233+
// the relationship instances for the relation. The relations will set
234+
// appropriate query constraint and entirely manages the hydrations.
235+
$query = $instance->newQuery();
236+
237+
return new BelongsToMany($query, $this, $collection, $foreignKey, $otherKey, $caller['function']);
238+
}
239+
202240
/**
203241
* Get a new query builder instance for the connection.
204242
*
@@ -274,4 +312,4 @@ public function __call($method, $parameters)
274312
return parent::__call($method, $parameters);
275313
}
276314

277-
}
315+
}

0 commit comments

Comments
 (0)