Skip to content

Commit 162869b

Browse files
committed
Convert manual _id's to MongoId objects, fixes #225
1 parent 23e21f3 commit 162869b

File tree

2 files changed

+33
-15
lines changed

2 files changed

+33
-15
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,13 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
4242
*/
4343
public function getIdAttribute($value)
4444
{
45-
// If there is an actual id attribute, then return that.
46-
if ($value) return $value;
45+
if ($value) return (string) $value;
4746

48-
// Return primary key value if present
49-
if (array_key_exists($this->getKeyName(), $this->attributes)) return $this->attributes[$this->getKeyName()];
47+
// Return _id as string
48+
if (array_key_exists('_id', $this->attributes))
49+
{
50+
return (string) $this->attributes['_id'];
51+
}
5052
}
5153

5254
/**
@@ -194,23 +196,23 @@ public function getTable()
194196
}
195197

196198
/**
197-
* Get an attribute from the model.
199+
* Set a given attribute on the model.
198200
*
199201
* @param string $key
200-
* @return mixed
202+
* @param mixed $value
203+
* @return void
201204
*/
202-
public function getAttribute($key)
205+
public function setAttribute($key, $value)
203206
{
204-
$attribute = parent::getAttribute($key);
205-
206-
// If the attribute is a MongoId object, return it as a string.
207-
// This is makes Eloquent relations a lot easier.
208-
if ($attribute instanceof MongoId)
207+
// Convert _id to MongoId.
208+
if ($key == '_id' and is_string($value))
209209
{
210-
return (string) $attribute;
210+
$this->attributes[$key] = new MongoId($value);
211+
}
212+
else
213+
{
214+
parent::setAttribute($key, $value);
211215
}
212-
213-
return $attribute;
214216
}
215217

216218
/**

tests/ModelTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,22 @@ public function testUpdate()
7979
$this->assertEquals(20, $check->age);
8080
}
8181

82+
public function testManualId()
83+
{
84+
$user = new User;
85+
$user->_id = '4af9f23d8ead0e1d32000000';
86+
$user->name = 'John Doe';
87+
$user->title = 'admin';
88+
$user->age = 35;
89+
$user->save();
90+
91+
$this->assertEquals(true, $user->exists);
92+
$this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id);
93+
94+
$raw = $user->getAttributes();
95+
$this->assertInstanceOf('MongoId', $raw['_id']);
96+
}
97+
8298
public function testDelete()
8399
{
84100
$user = new User;

0 commit comments

Comments
 (0)