1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Models\Traits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Arr; |
6
|
|
|
|
7
|
|
|
trait HasIdentifiableAttribute |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Get the name of the attribute that best defines the entry, from the user perspective. |
11
|
|
|
* |
12
|
|
|
* Rephrased: In most cases a user will NOT identify an Article because its ID is "4", but |
13
|
|
|
* because its name is "10 Ways to Burn Fat". This method returns the column in the database |
14
|
|
|
* that represents what is better to show to the user as an identifier rather than the ID. |
15
|
|
|
* Ex: name, title, label, description etc. |
16
|
|
|
* |
17
|
|
|
* @return string The name of the column that best defines this entry from the user perspective. |
18
|
|
|
*/ |
19
|
|
|
public function identifiableAttribute() |
20
|
|
|
{ |
21
|
|
|
if (property_exists($this, 'identifiableAttribute')) { |
22
|
|
|
return $this->identifiableAttribute; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return static::guessIdentifiableColumnName(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Get the most likely column in the db table that could be used as an identifiable attribute. |
30
|
|
|
* |
31
|
|
|
* @return string The name of the column in the database that is most likely to be a good indentifying attribute. |
32
|
|
|
*/ |
33
|
|
|
private static function guessIdentifiableColumnName() |
34
|
|
|
{ |
35
|
|
|
$instance = new static(); |
36
|
|
|
$connection = $instance->getConnectionWithExtraTypeMappings(); |
|
|
|
|
37
|
|
|
$table = $instance->getTableWithPrefix(); |
|
|
|
|
38
|
|
|
$columnNames = app('DatabaseSchema')->listTableColumnsNames($connection->getName(), $table); |
39
|
|
|
$indexes = app('DatabaseSchema')->listTableIndexes($connection->getName(), $table); |
40
|
|
|
|
41
|
|
|
// these column names are sensible defaults for lots of use cases |
42
|
|
|
$sensibleDefaultNames = ['name', 'title', 'description', 'label']; |
43
|
|
|
|
44
|
|
|
// if any of the sensibleDefaultNames column exists |
45
|
|
|
// that's probably a good choice |
46
|
|
|
foreach ($sensibleDefaultNames as $defaultName) { |
47
|
|
|
if (in_array($defaultName, $columnNames)) { |
48
|
|
|
return $defaultName; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
// if none of the sensible defaults exists |
53
|
|
|
// we get the first column from database |
54
|
|
|
// that is NOT indexed (usually primary, foreign keys) |
55
|
|
|
foreach ($columnNames as $columnName) { |
56
|
|
|
if (! in_array($columnName, $indexes)) { |
57
|
|
|
//check for convention "field<_id>" in case developer didn't add foreign key constraints. |
58
|
|
|
if (strpos($columnName, '_id') !== false) { |
59
|
|
|
continue; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $columnName; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// in case everything fails we just return the first column in database |
67
|
|
|
return Arr::first($columnNames); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|