如何在 Fat-Free Framework 中插入没有主键的多条记录

How to insert multiple records without primary key in Fat-Free Framework

我尝试插入多条记录到一个没有PK的table

for ($x = 0; $x < count($arr); $x++) {
    $name=$arr[$x];
    $user=new DB\SQL\Mapper($f3->get('DB'),'User');
    $user->name=$name;
    $user->save();
}

最后只有一条记录插入数据库

我也试了reset,还是只有一条记录

for ($x = 0; $x < count($arr); $x++) {
    $name=$arr[$x];
    $user=new DB\SQL\Mapper($f3->get('DB'),'User');
    $user->reset();
    $user->name=$name;
    $user->save();
}

如果我给这个table加上一个auto_increment主键就没问题了


更新 1:

我在网络浏览器中再次测试了这个问题。然后我得到了这个错误

Internal Server Error

PDOStatement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

所以我在save()之后无法执行$db->log(),现在我知道为什么只有一条记录了,因为php在第一个循环中停止了。

然后我启用general_log_file,我在文件

中找到了这个日志
160621 18:00:53    47 Connect   dev@localhost on my_db
           47 Query SET NAMES utf8
           47 Query SHOW columns FROM `my_db`.`UserAccount`
           47 Query INSERT INTO `UserAccount` (`name`) VALUES ('uName')
           47 Quit  

所以我尝试 运行 这个 SQL INSERT INTO `UserAccount` (`name`) VALUES ('uName') 并且没有错误。

我也检查了 /var/log/mysql.log 并且 /var/log/mysql.err 是空的。

现在我不知道如何找出问题所在

您的第二次尝试是正确的:

foreach($names as $name) {
    $user->reset();
    $user->name=$name;
    $user->save();
}

即使对于没有主键的映射器,它也能正常工作。

请记住,如果没有主键,您将无法更新 $user。引用自 docs:

Although the issue of having primary keys in all tables in your database is argumentative, F3 does not stop you from creating a data mapper object that communicates with a table containing no primary keys. The only drawback is: you can't delete or update a mapped record because there's absolutely no way for F3 to determine which record you're referring to.

注意:如果您仍在为记录插入而苦苦挣扎,您可以输出数据库日志 $db->log() 以查看哪些查询是 运行 幕后的。

更新:

为了在出现错误时能够输出DB日志,可以hook上ONERROR事件:

$f3->ONERROR=function($f3) {
  echo $f3->get('DB')->log();
}
$mapper->save();// SQL error will trigger ONERROR