Skip to content

Commit eed876e

Browse files
committed
Merge pull request #276 from v-six/master
Allows non-string _id
2 parents 96036ab + b445647 commit eed876e

File tree

2 files changed

+40
-6
lines changed

2 files changed

+40
-6
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,22 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
4545
/**
4646
* Custom accessor for the model's id.
4747
*
48-
* @return string
48+
* @param mixed $value
49+
*
50+
* @return mixed
4951
*/
5052
public function getIdAttribute($value)
5153
{
52-
if ($value) return (string) $value;
54+
if (!$value && array_key_exists('_id', $this->attributes)) {
55+
$value = $this->attributes['_id'];
56+
}
5357

5458
// Return _id as string
55-
if (array_key_exists('_id', $this->attributes))
56-
{
57-
return (string) $this->attributes['_id'];
59+
if ($value instanceof MongoId) {
60+
return (string) $value;
5861
}
62+
63+
return $value;
5964
}
6065

6166
/**

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)