使用PDO/MySQL获取不仅仅是最后一个插入ID


Get more than just last insert ID using PDO / MySQL

我正在编写一个小框架,我的目标是让我的开发人员在添加/插入资源后可以轻松地设置到资源详细信息页面的重定向。

通常,这与PDO::lastInsertID()一样简单,但我使用的不仅仅是ID来标识资源,我还使用了资源名称/标题的格式化版本。

例如,一个新的锦标赛可能被称为"测试锦标赛",因此它的资源URI将是domain.com/tournament/328-Test-tournance。

因此,当我在插入后重定向时,我需要重定向到"328测试锦标赛",而不仅仅是"328"。这是出于URL完整性的目的而设计的。我不希望人们访问ID和头衔不匹配的个人资源。

也就是说,在我插入后,我希望不仅能自动返回ID,还能自动返回我输入的内容的整个数据集,这样我就可以格式化标题并重定向。

我可以在控制器中这样做:

$this->TournamentModel->insert();
$id = PDO::lastInsertID();
$title = my_title_formatting_function($_POST['title']);
@header("Location: domain.com/tournament/{$id}-{$title}");

但我想要一个稍微优雅一点的解决方案:

$id=$this->TournamentModel->lastInsert();

其中lastInsert实际上是核心模型中的一个公共方法,它不仅检索最后一个插入的id,而且检索整行。然后我会在那里处理标题格式和id连接。

这样的东西存在吗?或者至少有一个PDO方法可以返回插入的表,这样我就可以使用表名和id构造查询了?

检查条令或推进。

它们是两个非常著名的对象关系映射器,以PDO为基础。ORM可以按照你的要求做,还有很多其他你会喜欢的功能,请查看。

"title"不属于Tournament对象吗?即

class TournamenentModel {
  private $id;
  private $title;
  public function setTitle($title) {
    $this->title = $title;
  }
  public function getTitleFormatted() {
    return my_title_formatting_function($this->title);
  }
}

在这种情况下,您的插入方法可能看起来像

PDO::save(array('title' => $this->title));

您的工作流程将沿着以下路线:

$tournament = new TournamentModel();
$tournament->setTitle($_POST['title']);
$tournament->insert();
$title = $tournament->getTitleFormatted();
@header("Location: domain.com/tournament/{$id}-{$title}");

在释放对象之前,标题一直保留在内存中,不需要保存然后从数据库中检索