Created
October 10, 2019 14:53
-
-
Save ahmadrio/52b5ee025a7242a6ca829a6e5a9c664c to your computer and use it in GitHub Desktop.
This file contains 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 | |
namespace App\Helpers\Traits; | |
trait SQLServerService | |
{ | |
/** | |
* Drop constraints default value column if exists | |
* | |
* @param $connection_name | |
* @param $table | |
* @param array $columns | |
* @return bool | |
*/ | |
public function dropConstraints($connection_name, $table, array $columns): bool | |
{ | |
if (Schema::connection($connection_name) && Schema::hasColumns($table, $columns)) { | |
$default_constraints = DB::select(" | |
SELECT df.name 'Constraint_Name', t.name 'Table_Name', c.NAME 'Column_Name' | |
FROM sys.default_constraints df | |
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id | |
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id | |
"); | |
if ($default_constraints !== null && count($default_constraints) > 0) { | |
foreach ($default_constraints as $column) { | |
if ($table === $column->Table_Name && in_array($column->Column_Name, $columns, true)) { | |
DB::statement("ALTER TABLE {$column->Table_Name} DROP CONSTRAINT {$column->Constraint_Name}"); | |
} | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment