【问题标题】:Sencha touch save new record and update id (key)Sencha touch 保存新记录并更新 id (key)
【发布时间】:2014-11-03 12:01:01
【问题描述】:

现在我使用这段代码来保存新的/现有的记录:

var values = this.getFrmDetails().getValues();
var record = this.getFrmDetails().getRecord();
var store  = Ext.getStore('usersStore');
record.set(values);
// Is this a new user?
if (record.data.id==-1)
{
    record.save();
    store.add(record);
}
store.load();
this.getMainView().pop();
  • 此代码运行良好,但它总是会再次保存和加载整个数据,我正在通过 id 跟踪记录,所以当我添加新记录时,我通过:-1 获取 ID。

  • 如果不使用 store.load(),新记录的 id 将始终为 -1,直到我重新加载我的应用程序。

如何使用在服务器端创建的 id 更新新记录?

  • 我将 REST 代理与 PHP 服务器端、MySQL 数据库一起使用。

  • 顺便说一下,在 Firebug 中,我总是看到 PUT 来获取新的/更新的记录。如何让 Sencha touch 发送 POST 仅用于新记录,PUT 仅用于更新现有记录?

  • 我有 autosync=true 在商店里。

谢谢

【问题讨论】:

    标签: extjs touch sencha-touch-2


    【解决方案1】:

    我使用的是 C# 而不是 PHP,但我使用了相同的 '-1' Id 技术。当我在存储中插入一条记录并与远程同步时,我返回插入的记录,存储从服务响应中获取值。

    var store = Ext.getStore('fooStore');
    var newFoo = {
        a: 'a',
        b: 'b'
    };
    
    store.add(newFoo) // here the record id would be -1
    store.sync({
        callback: function () {
            // here the id is the returned from the server
            // this is not needed if you have autoSync, It's just for clearness
        }
    });
    

    而我的 C# 代码结构是:

    function Foo Insert(Foo foo) {
        var myTable = new MyTable(); // In PHP would be different, but I guess that the idea is clear.
        var newRecord = myTable.Insert(foo); // The insert method returns the added record.
        return newRecord;
    }
    

    然后返回的记录将由模型或商店定义获取,并且 Id 将自动更新。如果使用这个,就不需要使用 store.load() 方法,因为响应中有更新所需的信息。

    对于请求 POST 而不是 PUT,您必须在模型/存储代理定义中使用它:

    // ...
    proxy: {
        // ...
        actionMethods: {
            create: 'POST',
            read: 'POST',
            update: 'POST',
            destroy: 'POST'
        }
        // ...
    }
    // ...
    

    【讨论】:

      【解决方案2】:

      我找到了解决办法:

      var newid=-1;
      record.save({success : function(res){newid=res.getId();}});
      record.data.id=newid;
      

      PHP端:

        $sql="SELECT LAST_INSERT_ID() id";
        $rs=mysql_query($sql);
        $db_field = mysql_fetch_assoc($rs);
        echo json_encode(array("success"=>$db_field['id'])); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        相关资源
        最近更新 更多