Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1c332f5

Browse files
committed
Casting "insertGetId" as an integer where appropriate. Fixes laravel#377.
Signed-off-by: Ben Corlett <[email protected]>
1 parent f627ef4 commit 1c332f5

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

src/Illuminate/Database/Query/Processors/Processor.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,17 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu
2929
{
3030
$query->getConnection()->insert($sql, $values);
3131

32-
return $query->getConnection()->getPdo()->lastInsertId($sequence);
32+
// If the table has an incrementing primary key, we will
33+
// receive the ID back as the next incremental value of
34+
// the primary key. However, sometimes we won't have
35+
// incrementing primary keys, in which case casting as
36+
// an ID would return 0.
37+
if (is_numeric($id = $query->getConnection()->getPdo()->lastInsertId($sequence)))
38+
{
39+
return (int) $id;
40+
}
41+
42+
return $id;
3343
}
3444

35-
}
45+
}

tests/Database/DatabaseProcessorTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@ public function tearDown()
1313
public function testInsertGetIdProcessing()
1414
{
1515
$pdo = $this->getMock('ProcessorTestPDOStub');
16-
$pdo->expects($this->once())->method('lastInsertId')->with($this->equalTo('id'))->will($this->returnValue(1));
16+
$pdo->expects($this->once())->method('lastInsertId')->with($this->equalTo('id'))->will($this->returnValue('1'));
1717
$connection = m::mock('Illuminate\Database\Connection');
1818
$connection->shouldReceive('insert')->once()->with('sql', array('foo'));
1919
$connection->shouldReceive('getPdo')->once()->andReturn($pdo);
2020
$builder = m::mock('Illuminate\Database\Query\Builder');
2121
$builder->shouldReceive('getConnection')->andReturn($connection);
2222
$processor = new Illuminate\Database\Query\Processors\Processor;
2323
$result = $processor->processInsertGetId($builder, 'sql', array('foo'), 'id');
24-
$this->assertEquals(1, $result);
24+
$this->assertSame(1, $result);
2525
}
2626

2727
}
@@ -31,4 +31,4 @@ class ProcessorTestPDOStub extends PDO {
3131
public function __construct() {}
3232
public function lastInsertId($sequence = null) {}
3333

34-
}
34+
}

0 commit comments

Comments
 (0)