Commit 162869b3 authored by Jens Segers's avatar Jens Segers

Convert manual _id's to MongoId objects, fixes #225

parent 23e21f33
...@@ -42,11 +42,13 @@ abstract class Model extends \Jenssegers\Eloquent\Model { ...@@ -42,11 +42,13 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
*/ */
public function getIdAttribute($value) public function getIdAttribute($value)
{ {
// If there is an actual id attribute, then return that. if ($value) return (string) $value;
if ($value) return $value;
// Return primary key value if present // Return _id as string
if (array_key_exists($this->getKeyName(), $this->attributes)) return $this->attributes[$this->getKeyName()]; if (array_key_exists('_id', $this->attributes))
{
return (string) $this->attributes['_id'];
}
} }
/** /**
...@@ -194,23 +196,23 @@ abstract class Model extends \Jenssegers\Eloquent\Model { ...@@ -194,23 +196,23 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
} }
/** /**
* Get an attribute from the model. * Set a given attribute on the model.
* *
* @param string $key * @param string $key
* @return mixed * @param mixed $value
* @return void
*/ */
public function getAttribute($key) public function setAttribute($key, $value)
{ {
$attribute = parent::getAttribute($key); // Convert _id to MongoId.
if ($key == '_id' and is_string($value))
// If the attribute is a MongoId object, return it as a string.
// This is makes Eloquent relations a lot easier.
if ($attribute instanceof MongoId)
{ {
return (string) $attribute; $this->attributes[$key] = new MongoId($value);
}
else
{
parent::setAttribute($key, $value);
} }
return $attribute;
} }
/** /**
......
...@@ -79,6 +79,22 @@ class ModelTest extends TestCase { ...@@ -79,6 +79,22 @@ class ModelTest extends TestCase {
$this->assertEquals(20, $check->age); $this->assertEquals(20, $check->age);
} }
public function testManualId()
{
$user = new User;
$user->_id = '4af9f23d8ead0e1d32000000';
$user->name = 'John Doe';
$user->title = 'admin';
$user->age = 35;
$user->save();
$this->assertEquals(true, $user->exists);
$this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id);
$raw = $user->getAttributes();
$this->assertInstanceOf('MongoId', $raw['_id']);
}
public function testDelete() public function testDelete()
{ {
$user = new User; $user = new User;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment