11.3.1 CRUD operations: CREATE
The Repository CREATE API:
/**
* @param mixed $id primary key(s)
* @param array|object $data new Entity data, or Entity object
* @param bool|string $validate TRUE to validate all, a named @orm-validate-subset, or FALSE to skip validation
* @param int $fetchMode fetch mode (FETCH_OBJ, FETCH_ARRAY, FETCH_JSON), FALSE to skip fetch after insert
* @param string|null $fetchSubset optional fetch subset as defined in @orm-subset
* @return mixed $Entity object or array if $fetchMode, TRUE if not $fetchMode, FALSE on failure
* @throws Exception
*/
function insert($id, $data=[], $validate=true, $fetchMode=self::FETCH_OBJ, $fetchSubset=null)
The insert() method as a rich polymorphic signature, that enable many different ways of use.
Key & data (params 1 and 2)
1) undefined primary key, values array
$data = [ ‘name’ => ‘John’, ‘age’ => 25 ];
$UserRepository->insert(null, $data);
2) undefined primary key, Object
$data = [ ‘name’ => ‘John’, ‘age’ => 25 ];
$User = new myproject\model\User($data);
$UserRepository->insert(null, $User);
3) defined primary key, value array
This will force the primary key with 1st param value
$data = [ ‘name’ => ‘John’, ‘age’ => 25 ];
$UserRepository->insert(12, $data);
4) defined primary key, Object
This will force the primary key with 1st param value
$data = [ ‘name’ => ‘John’, ‘age’ => 25 ];
$User = new myproject\model\User($data);
$UserRepository->insert(12, $User);
5) defined primary key inside Object
This will force the primary key with its array value
$data = [ 'id'=> 12, ‘name’ => ‘John’, ‘age’ => 25 ];
$User = new myproject\model\User($data);
$UserRepository->insert(null, $User);
Validation (param 3)
The CREATE API supports 3 validation modes:
# skip validation
$UserRepository->insert(null, $data, false);
# full validation (default mode)
$UserRepository->insert(null, $data, true);
# partial validation (validation subset)
$UserRepository->insert(null, $data, 'mysubset');
Fetch mode (param 4)
The CREATE API supports 4 fetch modes:
# FETCH_OBJ will return a model instance (default mode)
$User = $UserRepository->insert(null, $data, true, Repository::FETCH_OBJ);
# FETCH_ARRAY will return an array (with data type mapping)
$data = $UserRepository->insert(null, $data, true, Repository::FETCH_ARRAY);
# FETCH_JSON will return an array for JSON output (with data type mapping)
# it differs from FETCH_ARRAY on data/datetime casting
$data = $UserRepository->insert(null, $data, true, Repository::FETCH_JSON);
# FALSE to skip fetch after insert, returing void
(void) $UserRepository->insert(null, $data, true, false);
Fetch subset (param 5)
In case you specified one of FETCH_OBJ, FETCH_ARRAY or FETCH_JSON modes as param 4, you can optionally specify a subset of data to be fetched after insert, and returned.
$data = $UserRepository->insert(null, $data, true, Repository::FETCH_ARRAY, 'myfetchsubset');
Updated about 1 month ago