Skip to content

Commit 8c72d95

Browse files
committed
Adds support for _id of binary type (mongodb#1611)
1 parent dbe14c8 commit 8c72d95

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/Jenssegers/Mongodb/Eloquent/Model.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Illuminate\Support\Arr;
1010
use Illuminate\Support\Str;
1111
use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
12+
use MongoDB\BSON\Binary;
1213
use MongoDB\BSON\ObjectID;
1314
use MongoDB\BSON\UTCDateTime;
1415
use Illuminate\Contracts\Queue\QueueableEntity;
@@ -63,6 +64,8 @@ public function getIdAttribute($value = null)
6364
// Convert ObjectID to string.
6465
if ($value instanceof ObjectID) {
6566
return (string) $value;
67+
} elseif ($value instanceof Binary) {
68+
return (string) $value->getData();
6669
}
6770

6871
return $value;
@@ -172,7 +175,7 @@ protected function getAttributeFromArray($key)
172175
public function setAttribute($key, $value)
173176
{
174177
// Convert _id to ObjectID.
175-
if ($key == '_id' && is_string($value)) {
178+
if (($key == '_id' || Str::endsWith($key, '_id')) && is_string($value)) {
176179
$builder = $this->newBaseQueryBuilder();
177180

178181
$value = $builder->convertKey($value);
@@ -204,6 +207,8 @@ public function attributesToArray()
204207
foreach ($attributes as $key => &$value) {
205208
if ($value instanceof ObjectID) {
206209
$value = (string) $value;
210+
} elseif ($value instanceof Binary) {
211+
$value = (string) $value->getData();
207212
}
208213
}
209214

src/Jenssegers/Mongodb/Query/Builder.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use Illuminate\Support\Str;
1212
use Jenssegers\Mongodb\Connection;
1313
use MongoCollection;
14+
use MongoDB\BSON\Binary;
1415
use MongoDB\BSON\ObjectID;
1516
use MongoDB\BSON\Regex;
1617
use MongoDB\BSON\UTCDateTime;
@@ -843,6 +844,8 @@ public function convertKey($id)
843844
{
844845
if (is_string($id) && strlen($id) === 24 && ctype_xdigit($id)) {
845846
return new ObjectID($id);
847+
} elseif (strlen($id) === 16 && preg_match('~[^\x20-\x7E\t\r\n]~', $id) > 0) {
848+
return new Binary($id, Binary::TYPE_UUID);
846849
}
847850

848851
return $id;
@@ -903,7 +906,7 @@ protected function compileWheres()
903906
}
904907

905908
// Convert id's.
906-
if (isset($where['column']) && ($where['column'] == '_id' || Str::endsWith($where['column'], '._id'))) {
909+
if (isset($where['column']) && ($where['column'] == '_id' || Str::endsWith($where['column'], '_id'))) {
907910
// Multiple values.
908911
if (isset($where['values'])) {
909912
foreach ($where['values'] as &$value) {

0 commit comments

Comments
 (0)