在 laravel 中获取枚举选项 eloquent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26991502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:26:44  来源:igfitidea点击:

Get enum options in laravels eloquent

phplaravelenumseloquent

提问by barfoos

In my migration file, I gave my table pagesa enumfield with 2 possible values (as seen below). My question is, if it's possible to select these values with Laravels Eloquent?

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

$table->enum('status', array('draft','published'));

There are several Workarounds that I found, but there must be some "eloquent-native" way to handle this. My expected output would be this (that would be perfect!):

我发现了几种解决方法,但必须有一些“雄辩的本机”方法来处理这个问题。我的预期输出是这样的(那将是完美的!):

array('draft','published')

Thank you in advance!

先感谢您!

回答by lukasgeiter

Unfortunately, Laravel does not offer a solution for this. You will have to do it by yourself. I did some digging and found this answer

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

You can use that function and turn it into a method in your model class...

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

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;
    }
}

And you use it like this

你像这样使用它

$options = Page::getPossibleStatuses();

If you want you can also make it a bit more universally accessible and generic.

如果你愿意,你也可以让它更普遍、更通用。

First, create a BaseModel. All models should then extend from this class

首先,创建一个BaseModel. 所有模型都应该从这个类扩展

class BaseModel extends Eloquent {}

After that, put this function in there

之后,把这个功能放在那里

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;
}

You call this one like that

你这样称呼这个

$options = Page::getPossibleEnumValues('status');

回答by TheNatureBoy

Made a small improvement to lukasgeiter's function. The foreach loop in his answer is parsing the string. You can update the regex to do that for you.

对 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] : [];
}

回答by dom_hutton

As of L5.17 Eloquent does not include this functionality, instead you need to fall back to native QL. Here's an example that will work with SQL and in one line - returning an array like you asked.

从 L5.17 开始,Eloquent 不包含此功能,您需要回退到原生 QL。这是一个可以与 SQL 一起使用的示例,并且在一行中 - 返回您所要求的数组。

In the spirit of one liner complexity ;)

本着一种班轮复杂性的精神;)

I threw this in one of my view composers - it fetches the column from the table, explodes it and assembles the values in an array.

我把它扔给我的一个视图作曲家 - 它从表中获取列,分解它并将值组合到一个数组中。

I iterate over that in my views using a foreach.

我使用 foreach 在我的视图中迭代它。

explode (
    "','",
    substr (
      DB::select("  SHOW COLUMNS 
                    FROM ".(new \Namespace\Model)->getTable()." 
                    LIKE 'colName'"
      )[0]->Type,
      6,
      -2
    )
);