如何通过 php 知道哪些列在 postgres 中没有空约束?

How to know which columns have not null constraint in postgres via php?

我正在尝试通过 php 构建一些 html 输入元素以填充 postgres table 中的行。

我想将属性 "required" 添加到一些 html 输入元素(那些对应于具有 NOT NULL 约束的列)。

我如何知道哪些列具有该约束?

使用 PDO(和建议 here),您应该能够按如下方式完成它:

$q = $dbh->prepare("\d tablename");
$q->execute();
$table_fields = $q->fetchAll();
foreach ($table_fields as $field) {
    if (strpos($field['Modifiers'], 'not null') !== FALSE) {
         // this column ($field['Column']) has a "not null" constraint.
    }
}

编辑:如果您坚决使用 PostgreSQL PHP 扩展名:

$q = pg_query("\d tablename");
while ($row = pg_fetch_array($result)) {
    if (strpos($row['Modifiers'], 'not null') !== FALSE) {
         // this column ($row['Column']) has a "not null" constraint.
    }
}

使用 Pomm 它将为您执行这些查询以使用 CLI 检查您的数据库:

$ php vendor/bin/pomm.php pomm:inspect:relation test pika_chu
Relation public.pika_chu
+----+---------------+--------+-----------------------------------------------+---------+---------+
| pk | name          | type   | default                                       | notnull | comment |
+----+---------------+--------+-----------------------------------------------+---------+---------+
| *  | pika_chu_id   | int4   | nextval('pika_chu_pika_chu_id_seq'::regclass) | yes     |         |
|    | some_data     | int4   |                                               | yes     |         |
|    | nullable_data | bpchar |                                               | no      |         |
+----+---------------+--------+-----------------------------------------------+---------+---------+