ThinkPHP可以將更新和插入操作合并,并且支持直接讀取JSON格式的請求數據。
實現代碼:
~~~
public function saveBookInfo()
{
if (Request::isPost()) {
//如果包含ID則更新,否則新增
$data = $this->request->post();
$result = Db::name('book')->save($data);
$response = [
'errno' => 0,
'errmsg' => '數據更新成功',
'data' => $result
];
//返回新增或者更新成功的記錄數量
return json($response);
} else {
$response = [
'errno' => 1000,
'errmsg' => '錯誤的請求',
'data' => null
];
}
}
~~~
代碼解讀:
1. 首先控制器`Request::isPost()`判斷前端提交的請求類型是否是Post類型
2. 通過`$this->request->post()`獲取提交的數據。
3. 通過` Db::name('book')->save($data)`直接更新數據庫表,如果$data包含主鍵id字段,則更新,否則插入記錄
完整的代碼清單:
~~~
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Request;
class Book extends BaseController
{
/**
* 獲取圖書的分頁數據
*/
public function getBookList($page = 1, $pageSize = 10)
{
// 獲取數據集
$books = Db::name('book')->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $pageSize]);
$books = $books->toArray();
//轉換分頁器滿足約定的接口規范
$data = array(
'count' => $books['total'],
'currentPage' => $books['current_page'],
"pageSize" => $books['per_page'],
"totalPages" => $books['last_page'],
"data" => $books['data']
);
$response = [
'errno' => 0,
'errmsg' => '',
'data' => $data
];
return json($response);
}
/**
* 獲取所有的圖書列表
*/
public function getAllBook()
{
// 獲取數據集
$books = Db::name('book')->select();
$response = [
'errno' => 0,
'errmsg' => '',
'data' => $books
];
return json($response);
}
/**
* 獲取圖書數據
*/
public function getBookInfo($id = 0)
{
$book = Db::name('book')->where(['id' => $id])->find();
if ($book) {
$response = [
'errno' => 0,
'errmsg' => '',
'data' => $book
];
} else {
$response = [
'errno' => 1000,
'errmsg' => '沒有滿足條件的數據',
'data' => null
];
}
return json($response);
}
/**
* 刪除圖書數據
*/
public function deleteBookInfo($id)
{
$result = Db::name('book')->where(['id' => $id])->delete();
$response = null;
$response = [
'errno' => 0,
'errmsg' => '成功刪除記錄的數量',
'data' => $result
];
return json($response);
}
public function saveBookInfo()
{
if (Request::isPost()) {
//如果包含ID則更新,否則新增
$data = $this->request->post();
$result = Db::name('book')->save($data);
$response = [
'errno' => 0,
'errmsg' => '數據更新成功',
'data' => $result
];
//返回新增或者更新成功的記錄數量
return json($response);
} else {
$response = [
'errno' => 1000,
'errmsg' => '錯誤的請求',
'data' => null
];
}
}
}
~~~
## 測試接口
設置請求的數據格式為`Content-Type = application/json`,然后在body部分輸入要更新或者新增的記錄的JSON格式的信息。如果包含id字段則執行更新操作,否則執行新增操作。
