Skip to content

Commit

Permalink
Convert manual _id's to MongoId objects, fixes #225
Browse files Browse the repository at this point in the history
  • Loading branch information
jenssegers committed Jun 8, 2014
1 parent 23e21f3 commit 162869b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
32 changes: 17 additions & 15 deletions src/Jenssegers/Mongodb/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
*/
public function getIdAttribute($value)
{
// If there is an actual id attribute, then return that.
if ($value) return $value;
if ($value) return (string) $value;

// Return primary key value if present
if (array_key_exists($this->getKeyName(), $this->attributes)) return $this->attributes[$this->getKeyName()];
// Return _id as string
if (array_key_exists('_id', $this->attributes))
{
return (string) $this->attributes['_id'];
}
}

/**
Expand Down Expand Up @@ -194,23 +196,23 @@ public function getTable()
}

/**
* Get an attribute from the model.
* Set a given attribute on the model.
*
* @param string $key
* @return mixed
* @param mixed $value
* @return void
*/
public function getAttribute($key)
public function setAttribute($key, $value)
{
$attribute = parent::getAttribute($key);

// If the attribute is a MongoId object, return it as a string.
// This is makes Eloquent relations a lot easier.
if ($attribute instanceof MongoId)
// Convert _id to MongoId.
if ($key == '_id' and is_string($value))
{
return (string) $attribute;
$this->attributes[$key] = new MongoId($value);
}
else
{
parent::setAttribute($key, $value);
}

return $attribute;
}

/**
Expand Down
16 changes: 16 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,22 @@ public function testUpdate()
$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()
{
$user = new User;
Expand Down

0 comments on commit 162869b

Please sign in to comment.