CREATE TABLE public.tasks(
id integer NOT NULL DEFAULT nextval('tasks_id_seq'::regclass),
title character varying(255) NOT NULL,
status character varying(255) NOT NULL,
type character varying(255) NOT NULL,
CONSTRAINT tasks_pkey PRIMARY KEY (id),
CONSTRAINT tasks_status_check CHECK (status::text = ANY (ARRAY['Asignada'::character varying, 'Revision'::character varying, 'Cumplida'::character varying, 'Cancelada'::character varying, 'Diferida'::character varying, 'Retardada'::character varying]::text[])),
CONSTRAINT tasks_type_check CHECK (type::text = ANY (ARRAY['Academico-Docente'::character varying, 'Administrativas'::character varying, 'Creacion intelectual'::character varying, 'Integracion-Social'::character varying, 'Administrativo-Docente'::character varying, 'Produccion'::character varying]::text[])))
WITH ( OIDS=FALSE);
ALTER TABLE public.tasks
OWNER TO postgres;
鉴于此表,如何获得约束tasks_status_check和task_type_check的可用白名单值?
另外,我试图从Laravel那里做,Laravel创建约束而不是枚举。我已经调查了一段时间但找不到解决方案
我是在MySql中完成的,但我们正在转向PostgreSql
我的代码是这样的
trait EnumHelper {
public static function getEnumValues($field){
$instance = new static;
$type = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$field.'"'))[0]->Type;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$values = array();
foreach(explode(',', $matches[1]) as $value){
$values[] = trim($value, "'");
}
return $values;
}
}
提前致谢
答案 0 :(得分:1)
查询系统目录pg_constraint
的consrc
列以获取检查约束的文本表示。
如果您正在寻找文本文字(如本例所示),您可以使用正则表达式和函数regexp_matches()
,例如:
select conname, array_agg(matches[1]) as "white list"
from pg_constraint,
regexp_matches(consrc, '''(.+?)''', 'g') matches
where contype = 'c'
and conrelid = 'public.tasks'::regclass
group by 1;
conname | white list
--------------------+-----------------------------------------------------------------------------------------------------------------
tasks_type_check | {Academico-Docente,Administrativas,"Creacion intelectual",Integracion-Social,Administrativo-Docente,Produccion}
tasks_status_check | {Asignada,Revision,Cumplida,Cancelada,Diferida,Retardada}
(2 rows)
答案 1 :(得分:1)
我做到了,谢谢Klin!他的回答非常有用
trait EnumHelper {
public static function getEnumValues($field){
$instance = new static;
$types = DB::select("
select matches[1]
from pg_constraint,
regexp_matches(consrc, '''(.+?)''', 'g') matches
where contype = 'c'
and conname = '".$instance->getTable()."_".$field."_check'
and conrelid = 'public.tasks'::regclass;
");
$values = array();
foreach($types as $type){
$values[] = $type->matches;
}
return $values;
}
}
现在完美运作。