问题:
有没有办法将client.client_id
的值获取到 PHP 变量中,然后将其用作phone.client_id
的值?
上下文:
我有一个PostgreSQL数据库,我使用PHP与之通信。
我在数据库中有两个单独的表:
client (client_id[PK], client_name)
和
phone (phone_id[PK], client_id[FK], phone_number)
client_id
和phone_id
都创建为bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807
。
由于 id 是GENERATED ALWAYS AS IDENTITY
因此在 PHP 中将数据插入表中时无需指定它们:
$query = "INSERT INTO public.client (client_name) VALUES('" . $clientName . "')";
现在终于来回答我的问题:
每当我插入client
我也想插入一个phone
,phone
表需要保存对它所属client
的引用,并且它通过具有client_id
外键来实现。
如果我只是在 PHP 中创建 id,我可以在两个语句中使用该值INSERT
并最终获得正确的行为。
有没有办法将client.client_id
的值获取到 PHP 变量中,然后将其用作phone.client_id
的值?
感谢@ErmeSchultz和@MagnusEriksson我才能在此评论中找到解决方案。
我修改后的代码现在是:
// crafting the query so that the variable $query contains the value of the automatically generated client_id
$query = "INSERT INTO public.client (client_name) VALUES('" . $clientName . "') RETURNING client_id";
// getting an array of the elments contained inside $query
$row = pg_fetch_row($query);
// putting the first element inside $row into $client_id
$client_id = $row[0];
变量$client_id
现在包含client.client_id
!