如何将数据插入具有外键的表中

将数据插入具有外键约束的表的方法不止一种,但这是最简单的方法之一。
以下是非常适合的分步教程。

下面假设我们有两个表,它们的布局不是非常重要,因为我们将只关注如何存储用户代理。

表名是 request_log 和 user_agents。

  • request_log 表是在 ua_id 列上使用外键约束创建的。
  • 各个 ua_id 字段的内容必须与 user_agents 表中的唯一 id 列对应。

选择是通过具有唯一索引的 ua_hash 列执行的;该列包含用于快速查找的 md5 哈希值。

  1. 就我而言,第一个选择查询可能如下所示:
$result = $db->prepared_query->("select id from user_agents where ua_hash = ?",
  [md5($user_agent)]
);

2.现在我必须检查查询是否失败以及是否实际返回了任何内容:

if (false === $result) {
   //Do something if the query fails
   //This should not happen, so we should probably just log the event..
}
if ($result->num_rows === 0) {
   //If the query returned nothing, we are dealing with an unknown user agent,
   //and we should first insert a new row in the "user_agents" table before we continue
   $result = $db->prepared_query->("insert into user_agent (ua_hash, ua_string) values(?, ?)",
     [md5($user_agent), $user_agent]
   );
   if(false === $result) {
     //If the query failed, be sure to log this event...
   }
}

ua_hash 只是为了更快地查找,我们想在此列上添加索引。

  1. 现在我们终于可以在 request_log 表中插入一个新行了:
//Make an associative array
$ua_row = $result->fetch_assoc();
//Now we can finally send an insert to the "request_log" table
$result = $db->prepared_query->("insert into request_log (ip_address, ua_id) values(?, ?)",
     [$ip_address, $ua_row['id']]
);

另一种插入行的方法是使用 subquery ,但请记住,如果 user_agents 表中尚不存在用户代理,则此类查询可能会失败。

日期:2020-06-02 22:17:06 来源:oir作者:oir