Skip to content

Commit c22670a

Browse files
committed
Allows an _id attribute of another type than string
1 parent 96036ab commit c22670a

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,11 @@ public function getIdAttribute($value)
5454
// Return _id as string
5555
if (array_key_exists('_id', $this->attributes))
5656
{
57-
return (string) $this->attributes['_id'];
57+
if ($this->attributes['_id'] instanceof MongoId) {
58+
return (string) $this->attributes['_id'];
59+
}
60+
61+
return $this->attributes['_id'];
5862
}
5963
}
6064

tests/ModelTest.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ public function testUpdate()
7979
$this->assertEquals(20, $check->age);
8080
}
8181

82-
public function testManualId()
82+
public function testManualStringId()
8383
{
8484
$user = new User;
8585
$user->_id = '4af9f23d8ead0e1d32000000';
@@ -93,6 +93,35 @@ public function testManualId()
9393

9494
$raw = $user->getAttributes();
9595
$this->assertInstanceOf('MongoId', $raw['_id']);
96+
97+
$user = new User;
98+
$user->_id = 'customId';
99+
$user->name = 'John Doe';
100+
$user->title = 'admin';
101+
$user->age = 35;
102+
$user->save();
103+
104+
$this->assertEquals(true, $user->exists);
105+
$this->assertEquals('customId', $user->_id);
106+
107+
$raw = $user->getAttributes();
108+
$this->assertInternalType('string', $raw['_id']);
109+
}
110+
111+
public function testManualIntId()
112+
{
113+
$user = new User;
114+
$user->_id = 1;
115+
$user->name = 'John Doe';
116+
$user->title = 'admin';
117+
$user->age = 35;
118+
$user->save();
119+
120+
$this->assertEquals(true, $user->exists);
121+
$this->assertEquals(1, $user->_id);
122+
123+
$raw = $user->getAttributes();
124+
$this->assertInternalType('integer', $raw['_id']);
96125
}
97126

98127
public function testDelete()

0 commit comments

Comments
 (0)