在laravels中获得enum选项雄辩

bar*_*oos 16 php enums laravel eloquent

在我的迁移文件中,我为表格提供pages了一个enum包含2个可能值的字段(如下所示).我的问题是,如果有可能选择与Laravels这些值雄辩

$table->enum('status', array('draft','published'));
Run Code Online (Sandbox Code Playgroud)

我找到了几种解决方法,但必须有一些"雄辩本地"的方法来处理这个问题.我的预期输出将是这个(这将是完美的!):

array('draft','published')
Run Code Online (Sandbox Code Playgroud)

先感谢您!

luk*_*ter 13

不幸的是,Laravel没有为此提供解决方案.你必须自己做.我做了一些挖掘并找到了答案

您可以使用该函数并将其转换为模型类中的方法...

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

你就这样使用它

$options = Page::getPossibleStatuses();
Run Code Online (Sandbox Code Playgroud)

如果你想要,你也可以使它更普遍可访问和通用.

首先,创建一个BaseModel.然后所有模型都应从此类扩展

class BaseModel extends Eloquent {}
Run Code Online (Sandbox Code Playgroud)

之后,将此功能放在那里

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;
}
Run Code Online (Sandbox Code Playgroud)

你这样称呼这个

$options = Page::getPossibleEnumValues('status');
Run Code Online (Sandbox Code Playgroud)

  • 为什么不为此使用专用特性? (2认同)

The*_*Boy 5

对lukasgeiter的功能做了一个小改进。他的答案中的 foreach 循环正在解析字符串。您可以更新正则表达式来为您做到这一点。

/**
 * Retrieves the acceptable enum fields for a column
 *
 * @param string $column Column name
 *
 * @return array
 */
public static function getPossibleEnumValues ($column) {
    // Create an instance of the model to be able to get the table name
    $instance = new static;

    // Pulls column string from DB
    $enumStr = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$column.'"'))[0]->Type;

    // Parse string
    preg_match_all("/'([^']+)'/", $enumStr, $matches);

    // Return matches
    return isset($matches[1]) ? $matches[1] : [];
}
Run Code Online (Sandbox Code Playgroud)