one*_*eno 5 ember.js ember-data
如果我尝试用类似的内容创建记录
var myObject = App.ModelName.createRecord( data );
myObject.get("transaction").commit();
Run Code Online (Sandbox Code Playgroud)
永远不会设置myObject的ID。
这表示id生成应由EmberData处理(第一个响应)。那么应该怎么办?新ID在哪里确定。应该不应该回调API以获得有效的ID?
ID 是您的记录的主键,由您的数据库创建,而不是由 Ember 创建。这是提交给 REST post 的 JSON 结构,注意没有 ID。
{"post":{"title":"c","author":"c","body":"c"}}
Run Code Online (Sandbox Code Playgroud)
在 REST Post 函数中,您必须获取最后一个插入 ID,并使用以下 JSON 结构将其与模型数据的其余部分一起返回到 Ember。注意 ID,即最后一个插入 ID。您必须使用数据库 api 手动获取最后一个插入 ID。
{"post":{"id":"20","title":"c","author":"c","body":"c"}}
Run Code Online (Sandbox Code Playgroud)
这是我的 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
//);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3172 次 |
| 最近记录: |