Skip to content

Commit d78e126

Browse files
committed
Allow execution of collection methods on embedded relations
1 parent f6e43f5 commit d78e126

File tree

4 files changed

+453
-422
lines changed

4 files changed

+453
-422
lines changed

phpunit.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
</testsuite>
3535
<testsuite name="relations">
3636
<directory>tests/RelationsTest.php</directory>
37+
<directory>tests/EmbeddedRelationsTest.php</directory>
3738
</testsuite>
3839
<testsuite name="mysqlrelations">
3940
<directory>tests/RelationsTest.php</directory>

src/Jenssegers/Mongodb/Relations/EmbedsMany.php

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,36 +19,17 @@ public function getResults()
1919
}
2020

2121
/**
22-
* Find an embedded model by its primary key.
22+
* Simulate order by method.
2323
*
24-
* @param mixed $id
25-
* @return \Illuminate\Database\Eloquent\Collection
24+
* @param string $column
25+
* @param string $direction
26+
* @return Illuminate\Database\Eloquent\Collection
2627
*/
27-
public function find($id)
28+
public function orderBy($column, $direction = 'asc')
2829
{
29-
if ($id instanceof Model) $id = $id->getKey();
30-
31-
$primaryKey = $this->related->getKeyName();
30+
$descending = strtolower($direction) == 'desc';
3231

33-
// Traverse all embedded records and find the first record
34-
// that matches the given primary key.
35-
$record = array_first($this->getEmbedded(), function($itemKey, $record) use ($primaryKey, $id)
36-
{
37-
return $record[$primaryKey] == $id;
38-
});
39-
40-
return $record ? $this->toModel($record) : null;
41-
}
42-
43-
/**
44-
* Check if a model is already embedded.
45-
*
46-
* @param mixed $key
47-
* @return bool
48-
*/
49-
public function contains($key)
50-
{
51-
return ! is_null($this->find($key));
32+
return $this->getResults()->sortBy($column, SORT_REGULAR, $descending);
5233
}
5334

5435
/**
@@ -314,4 +295,22 @@ protected function setEmbedded($models)
314295
return parent::setEmbedded(array_values($models));
315296
}
316297

298+
/**
299+
* Handle dynamic method calls to the relationship.
300+
*
301+
* @param string $method
302+
* @param array $parameters
303+
* @return mixed
304+
*/
305+
public function __call($method, $parameters)
306+
{
307+
// Collection methods
308+
if (method_exists('Illuminate\Database\Eloquent\Collection', $method))
309+
{
310+
return call_user_func_array(array($this->getResults(), $method), $parameters);
311+
}
312+
313+
return parent::__call($method, $parameters);
314+
}
315+
317316
}

0 commit comments

Comments
 (0)