Niestety, Laravel nie oferuje rozwiązania tego problemu. Będziesz musiał to zrobić sam. Zrobiłem trochę kopanie i stwierdziliśmy this answer
Można użyć tej funkcji i przekształcić go w sposób w swojej klasie modelu ...
class Page extends Eloquent {
public static function getPossibleStatuses(){
$type = DB::select(DB::raw('SHOW COLUMNS FROM pages WHERE Field = "type"'))[0]->Type;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$values = array();
foreach(explode(',', $matches[1]) as $value){
$values[] = trim($value, "'");
}
return $values;
}
}
I go używać jak to
$options = Page::getPossibleStatuses();
If chcesz, możesz również uczynić go bardziej uniwersalnym i uniwersalnym. Najpierw utwórz BaseModel
. Wszystkie modele powinny następnie rozciągać się od tej klasy
class BaseModel extends Eloquent {}
Po tym, umieścić tę funkcję tam
public static function getPossibleEnumValues($name){
$instance = new static; // create an instance of the model to be able to get the table name
$type = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$name.'"'))[0]->Type;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach(explode(',', $matches[1]) as $value){
$v = trim($value, "'");
$enum[] = $v;
}
return $enum;
}
Nazywasz to kogoś takiego
$options = Page::getPossibleEnumValues('status');
Dlaczego nie użyć w tym celu dedykowanej cechy? – ozanmuyes
Oczywiście możesz użyć cechy, jeśli chcesz – lukasgeiter
Laravel powinien dodać to do każdej Eloquent Class, może jako Cecha –