Commit 03cee24c authored by Jens Segers's avatar Jens Segers

Allow custom id's, fixes #24

parent 18a1010c
......@@ -48,7 +48,7 @@ class Builder extends \Illuminate\Database\Query\Builder {
*/
public function find($id, $columns = array('*'))
{
return $this->where('_id', '=', new MongoID((string) $id))->first($columns);
return $this->where('_id', '=', $this->convertKey($id))->first($columns);
}
/**
......@@ -500,6 +500,22 @@ class Builder extends \Illuminate\Database\Query\Builder {
return 0;
}
/**
* Convert a key to MongoID if needed
*
* @param mixed $id
* @return mixed
*/
protected function convertKey($id)
{
if (is_string($id) && strlen($id) === 24 && ctype_xdigit($id))
{
return new MongoId($id);
}
return $id;
}
/**
* Compile the where array
*
......@@ -522,13 +538,13 @@ class Builder extends \Illuminate\Database\Query\Builder {
{
foreach ($where['values'] as &$value)
{
$value = ($value instanceof MongoID) ? $value : new MongoID($value);
$value = $this->convertKey($value);
}
}
// Single value
else
{
$where['value'] = ($where['value'] instanceof MongoID) ? $where['value'] : new MongoID($where['value']);
$where['value'] = $this->convertKey($where['value']);
}
}
......
......@@ -228,4 +228,19 @@ class QueryTest extends PHPUnit_Framework_TestCase {
$this->assertEquals(array('sharp', 'round'), $types);
}
public function testCustomId()
{
DB::collection('items')->insert(array(
array('_id' => 'knife', 'type' => 'sharp', 'amount' => 34),
array('_id' => 'fork', 'type' => 'sharp', 'amount' => 20),
array('_id' => 'spoon', 'type' => 'round', 'amount' => 3)
));
$item = DB::collection('items')->find('knife');
$this->assertEquals('knife', $item['_id']);
$item = DB::collection('items')->where('_id', 'fork')->first();
$this->assertEquals('fork', $item['_id']);
}
}
\ No newline at end of file
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