当我使用foreach时,为什么我的代码只向DB插入一个

时间:2018-04-30 11:38:02

标签: php phalcon phalcon-orm

我需要使用foreach将数据插入数据库 但我的代码只插入最后一个,请帮我找出原因?

发布数据

{
"APIPassword": "Test",
"Method": "Transfer",
"Data": [
    {
        "Account": "Test01",
        "Amount": 100,
        "TransactionNo": "Test1",
        "dbID": "Bet1"
    },
    {
        "Account": "Test02",
        "Amount": -100,
        "TransactionNo": "Test2",
        "dbID": "Bet2"
    }
]}

我的代码

$apiPassword = $data['APIPassword'];
$method = $data['Method'];
$datas = $data['Data'];

$db = new db();

foreach ($datas as $data) {
    $db->userId = '1';
    $db->account = $data['Account'];
    $db->amount = (float) $data['Amount'];
    $db->transactionNo = $data['TransactionNo'];
    $db->dbID = $data['dbID'];
    $db->save();
}

提交时的结果

"Account": "Test02",
    "Amount": -100,
    "TransactionNo": "Test2",
    "db": "Bet2"

2 个答案:

答案 0 :(得分:1)

每次在for循环中都需要实例化一个新的db对象,在当前代码中,你在循环的每次迭代中使用相同的对象。

将您的代码更改为:

$apiPassword = $data['APIPassword'];
$method = $data['Method'];
$datas = $data['Data'];

foreach ($datas as $data) {
    $db = new db();
    $db->userId = '1';
    $db->account = $data['Account'];
    $db->amount = (float) $data['Amount'];
    $db->transactionNo = $data['TransactionNo'];
    $db->dbID = $data['dbID'];
    $db->save();
}

答案 1 :(得分:0)

什么是dl = [ "a.b.c.domain.com", "d.e.domain.com", "f.domain.com" ] N = 2 print([x for x in dl if x.count(".")-1 <= N]) # prints ["d.e.domain.com", "f.domain.com"] $db = new db();对应于模型?试试这样:

db

也许在您的应用的后期阶段,您可能想要更新记录。如果foreach ($datas as $data) { $db = new db(); // <-- Important part $db->userId = '1'; $db->account = $data['Account']; $db->amount = (float) $data['Amount']; $db->transactionNo = $data['TransactionNo']; $db->dbID = $data['dbID']; $db->save(); } 是您唯一的记录密钥,您将执行以下操作:

dbID