使用createRecord在ember数据中设置id

时间:2013-06-14 20:06:09

标签: ember.js ember-data

如果我尝试创建类似

的记录
var myObject = App.ModelName.createRecord( data );
myObject.get("transaction").commit();

永远不会设置myObject的id。

This表示id生成应该由EmberData处理(第一个响应)。那应该发生什么?确定新ID的位置。难道不应该回调API以获得有效的ID吗?

2 个答案:

答案 0 :(得分:2)

ID是您的记录的主键,由您的数据库创建,而不是由Ember创建。这是JSON结构提交到REST帖子,注意没有ID。

{"post":{"title":"c","author":"c","body":"c"}}

在REST Post函数中,您必须获取最后一个插入ID,并使用以下JSON结构将其余的模型数据返回给Ember。注意ID,即最后一个插入ID。您必须使用DB api手动获取最后一个插入ID。

{"post":{"id":"20","title":"c","author":"c","body":"c"}}

这是我的REST帖子的示例代码。我使用PHP REST Slim框架编写了这个代码:

$app->post('/posts', 'addPost'); //insert new post

function addPost() {
    $request = \Slim\Slim::getInstance()->request();
    $data = json_decode($request->getBody());

    //logging json data received from Ember!
    $file = 'json1.txt';
    file_put_contents($file, json_encode($data));
    //exit;

    foreach($data as $key => $value) {
        $postData = $value;
    }

    $post = new Post();
    foreach($postData as $key => $value) {

        if ($key == "title")
            $post->title = $value;

        if ($key == "author")
            $post->author = $value;

        if ($key == "body")
            $post->body = $value;   
    }

    //logging
    $file = 'json2.txt';
    file_put_contents($file, json_encode($post));

    $sql = "INSERT INTO posts (title, author, body) VALUES (:title, :author, :body)";

    try
    {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("title", $post->title);
        $stmt->bindParam("author", $post->author);
        $stmt->bindParam("body", $post->body);
        $stmt->execute();

        $insertID =  $db->lastInsertId(); //get the last insert ID
        $post->id = $insertID;

        //prepare the Ember Json structure
        $emberJson = array("post" => $post);

        //logging
        $file = 'json3.txt';
        file_put_contents($file, json_encode($emberJson));

        //return the new model back to Ember for model update
        echo json_encode($emberJson);
    }
    catch(PDOException $e)
    {
        //$errorMessage = $e->getMessage();
        //$data = Array(
        //  "insertStatus" => "failed",
        //  "errorMessage" => $errorMessage
        //);
    }
}

答案 1 :(得分:2)

使用某些REST适配器,例如 Firebase ,您可以将id定义为您要创建的记录的变量。

App.User = DS.Model.extend({
  firstName: DS.attr('string')
});

var sampleUser = model.store.createRecord('user', {
  id: '4231341234891234',
  firstName: 'andreas'
});

sampleUser.save();

数据库中的JSON(Firebase)

"users": {
  "4231341234891234": {
    "firstName": "andreas"
  }
}