json
首先把 ‘region’ 字段改为 array 类型
public function getRegionAttribute($value)
{
return json_decode($value,true);
}
public function setRegionAttribute($value)
{
$this->attributes['region'] = json_encode($value);
}
enum
app\Libs\EnumOptions.php
<?php
namespace App\Libs;
use Exception;
use Illuminate\Support\Facades\DB;
class EnumOptions
{
private $_table;
private $_column;
private $_options;
/**
* EnumOptions constructor.
* @param $table
* @param $column
* @throws Exception
*/
public function __construct($table, $column)
{
$columnInfo = $this->getColumnDefinition($table, $column);
$type = $columnInfo->Type;
if (strstr(strtolower($type), 'enum')) {
$this->_options = explode("','", trim(substr($type, strlen('enum('), -1), "'"));
} else if (strstr(strtolower($columnInfo->Type), 'set')) {
$this->_options = explode("','", trim(substr($type, strlen('set('), -1), "'"));
} else {
$this->_options = [];
}
}
/**
* @param $table
* @param $column
* @return mixed
* @throws Exception
*/
private function getColumnDefinition($table, $column)
{
$this->_table = DB::select("SHOW FULL COLUMNS FROM `" . $table . "`");
foreach ($this->_table as $tableInfo) {
if ($tableInfo->Field == $column) {
$this->_column = $tableInfo;
return $tableInfo;
}
}
throw new Exception('Column \'' . $table . '.' . $column . '\' doesn\'t exist ');
}
/**
* @return array
*/
public function getOptions()
{
return $this->_options;
}
/**
* EnumOptions constructor.
*
* @param $table
* @param $column
* @throws Exception
*
* public function __construct($table, $column)
* {
* // $column = DB::getDoctrineSchemaManager();
* $column = DB::getDoctrineColumn($table, $column);
* if (strstr(strtolower($column->getType()), 'enum')) {
* return $column->getCustomSchemaOption('options');
* } else {
* throw new Exception('字段属性错误');
* }
* }
* @todo 只对emit类型好使,set类型没有options数据,该方法暂时用自写方法替代
*/
}
查询数据
$sex = (new EnumOptions('position', 'sex'))->getOptions();
}
set
在模型中定义
// 如果类型是set,需要定义下面这个
public function setBenefitsAttribute($value)
{
$this->attributes['benefits'] = implode(",",$value);
}
public function getBenefitsAttribute()
{
return explode(",", $this->attributes['benefits']);
}
查
$benefits = (new EnumOptions('position', 'benefits'))->getOptions();