1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
namespace Database;
use Illuminate\Support\Facades\DB;
/**
* Class DisablesForeignKeys.
*/
trait DisableForeignKeys
{
/**
* @var array
*/
private $commands = [
'mysql' => [
'enable' => 'SET FOREIGN_KEY_CHECKS=1;',
'disable' => 'SET FOREIGN_KEY_CHECKS=0;',
],
'sqlite' => [
'enable' => 'PRAGMA foreign_keys = ON;',
'disable' => 'PRAGMA foreign_keys = OFF;',
],
'sqlsrv' => [
'enable' => 'EXEC sp_msforeachtable @command1="print \'?\'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all";',
'disable' => 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";',
],
'pgsql' => [
'enable' => 'SET CONSTRAINTS ALL IMMEDIATE;',
'disable' => 'SET CONSTRAINTS ALL DEFERRED;',
],
];
/**
* Disable foreign key checks for current db driver.
*/
protected function disableForeignKeys()
{
DB::statement($this->getDisableStatement());
}
/**
* Enable foreign key checks for current db driver.
*/
protected function enableForeignKeys()
{
DB::statement($this->getEnableStatement());
}
/**
* Return current driver enable command.
*
* @return mixed
*/
private function getEnableStatement()
{
return $this->getDriverCommands()['enable'];
}
/**
* Return current driver disable command.
*
* @return mixed
*/
private function getDisableStatement()
{
return $this->getDriverCommands()['disable'];
}
/**
* Returns command array for current db driver.
*
* @return mixed
*/
private function getDriverCommands()
{
return $this->commands[DB::getDriverName()];
}
}