|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Models\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use DB; |
|
6
|
|
|
use Illuminate\Support\Facades\Config; |
|
7
|
|
|
|
|
8
|
|
|
/* |
|
9
|
|
|
|-------------------------------------------------------------------------- |
|
10
|
|
|
| Methods for working with the Enum column in MySQL. |
|
11
|
|
|
|-------------------------------------------------------------------------- |
|
12
|
|
|
*/ |
|
13
|
|
|
trait HasEnumFields |
|
14
|
|
|
{ |
|
15
|
|
|
public static function getPossibleEnumValues($field_name) |
|
16
|
|
|
{ |
|
17
|
|
|
$instance = new static(); // create an instance of the model to be able to get the table name |
|
18
|
|
|
|
|
19
|
|
|
$connection = $instance->getConnection(); |
|
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
$table_prefix = Config::get('database.connections.'.$connection->getName().'.prefix'); |
|
22
|
|
|
|
|
23
|
|
|
try { |
|
24
|
|
|
$select = app()->version() < 10 ? |
|
|
|
|
|
|
25
|
|
|
DB::raw('SHOW COLUMNS FROM `'.$table_prefix.$instance->getTable().'` WHERE Field = "'.$field_name.'"') : |
|
|
|
|
|
|
26
|
|
|
DB::raw('SHOW COLUMNS FROM `'.$table_prefix.$instance->getTable().'` WHERE Field = "'.$field_name.'"')->getValue($connection->getQueryGrammar()); |
|
27
|
|
|
|
|
28
|
|
|
$type = $connection->select($select)[0]->Type; |
|
29
|
|
|
} catch (\Exception $e) { |
|
30
|
|
|
abort(500, 'Enum field type is not supported - it only works on MySQL. Please use select_from_array instead.', ['developer-error-exception']); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
preg_match('/^enum\((.*)\)$/', $type, $matches); |
|
|
|
|
|
|
34
|
|
|
$enum = []; |
|
35
|
|
|
foreach (explode(',', $matches[1]) as $value) { |
|
36
|
|
|
$enum[] = trim($value, "'"); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $enum; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public static function getEnumValuesAsAssociativeArray($field_name) |
|
43
|
|
|
{ |
|
44
|
|
|
$instance = new static(); |
|
45
|
|
|
$enum_values = $instance->getPossibleEnumValues($field_name); |
|
46
|
|
|
|
|
47
|
|
|
$array = array_flip($enum_values); |
|
48
|
|
|
|
|
49
|
|
|
foreach ($array as $key => $value) { |
|
50
|
|
|
$array[$key] = $key; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return $array; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|