(沒有版本資訊,可能只存在於 Git 中)
CollectionAdd::__construct — CollectionAdd 建構函式
用於將文件新增至集合;從 Collection 物件呼叫。
此函式沒有參數。
範例 #1 mysql_xdevapi\CollectionAdd::__construct() 範例
<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$collection = $schema->getCollection("people");
// 新增兩份文件
$collection
->add('{"name": "Fred", "age": 21, "job": "Construction"}')
->execute();
$collection
->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
->execute();
// 使用單個 JSON 物件新增兩份文件
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')
->execute();
// 從最後一次 add() 取得產生的 ID 列表
$ids = $result->getGeneratedIds();
print_r($ids);
?>
上述範例將輸出類似以下的內容
Array ( [0] => 00005b6b53610000000000000056 [1] => 00005b6b53610000000000000057 )
備註:
如範例所示,MySQL Server 8.0 或更高版本會產生唯一的 _id。如果使用 MySQL Server 5.7,則必須手動定義 _id 欄位。