-
-
Save ju5t/72fa0ff08f34bf73957851d708154fb6 to your computer and use it in GitHub Desktop.
Eloquent Model event hook to allow inserting primary keys into SQL Server tables with IDENTITY_INSERT = off
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait PrimaryKey | |
{ | |
protected $primaryKey = 'TransactionID'; | |
public static function bootPrimaryKey() | |
{ | |
static::creating(function(self $model) { | |
$pkColumn = $model->primaryKey; | |
$tableName = $model->table; | |
if (empty($model->$pkColumn)) { | |
$lastPk = $model->getQuery()->max($pkColumn); | |
$model->$pkColumn = $lastPk + 1; | |
} | |
$model->getConnection()->beforeExecuting(function($query, $bindings, \Illuminate\Database\Connection $connection) use ($tableName) { | |
// Perform some rudimentary escaping. SQL Server allows any character in the table name | |
// so we will remove characters SQL Server uses to wrap the table name and wrap | |
// it ourselves. | |
$tableName = str_replace(['[', ']', '`'], '', $tableName); | |
$connection->getPdo()->exec('SET IDENTITY_INSERT ['.$tableName.'] ON;'); | |
$connection->commit(); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment