How to retrieve the insert ID when inserting data via Connection::insert()? - cakephp

I want use connectionManager in piece of my project.
how can I access insert id by using connectionManager::insert
for example:
$connection = ConnectionManager::get('default');
$connection->insert('cities',
[
'name' => $city,
'country' => $country_code,
]
);

There is no need to do that, this will "just work" whether you create an explicit cities table class or not:
use Cake\ORM\TableRegistry;
$table = TableRegistry::get('cities');
$entity = $table->newEntity(
[
'name' => $city,
'country' => $country_code,
]
);
$table->save($entity);
$cityId = $entity->id;
But how?
Calling insert, returns a statement object:
$connection = ConnectionManager::get('default');
$statement = $connection->insert('cities',
[
'name' => $city,
'country' => $country_code,
]
);
Which can then be used to find the last insert id:
$cityId = $statement->lastInsertId('cities');
This is one of the things you don't need to worry about using the ORM as designed as the save method takes care of that automatically.

Related

Retrieve data from associated database in cakephp

I have an Entries table with users_id as a foreign key to the Users table.
I have set the belongsTo association in the EntriesTable like so:
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
After that I wrote this in the EntriesController:
$entries = TableRegistry::get('Entries');
$query = $entries->findByTitle($title)
->contain(['Users']);
$entry = $query->first();
$this->set('entry', $entry);
In the VIEW template of the Entries I have to show the username field of the user that wrote the Entry.
I am aware that in previous versions of CakePHP 1, I could just write $entry['User']['username'] to retrieve the username of the User who wrote the Entry. Now that I am using CakePHP 3.6, it doesn't seem to work. How do I perform the same task in CakePHP 3?
You can write like below
In controller
public function view($title)
{
$entry = $this->Entries->findByTitle($title)->contain(['Users']);
$entry = $entry->first();
$this->set('entry', $entry);
}
OR
public function view($title)
{
$query = $this->Entries->find('all', [
'where' => ['Entries.title' => $title],
'contain' => ['Users']
]);
$entry = $query->first();
$this->set('entry', $entry);
}
In view
<?= $entry->user->username ?>
So in cakephp you were loading Model of its controller, which is done as default,you can directly create an find() method in same controller,if you want to find from other table/ model you can do is-
a. $this->Entries->otherTableName()->find()->all();
b. $tableName= $this->loadModel('tableName');
$tableName->find();

How to create name value pair array in yii2

i am trying to create an Array in yii2 in following format
[
['id'=>'2', 'name'=>'ABC'],
['id'=>'3', 'name'=>'DEF']
]
So far i have tried to use ArrayHelper class but if i map using it than it removes the key part from the array,i need to create the array in exact this format
$data = User::find()
->where(['id' => $id])
->orderBy('id DESC')
->all();
As you know after this code i get the data in ActiveRecord format so i need to convert them to id and name array only,i dont need any other data.
I tried doing this
$data2 = ArrayHelper::map($data, 'id', 'name');
But returns the data in following format
[
['2'=>'ABC'],
['3'=>'DEF']
]
I have tried this as well
$data = MainCategory::find()->select('id,name')
->where(['id' => $id])
->orderBy('id DESC')
->asArray()->all();
But its returning the array in following format
[
'0' =>
[
'id'=>'2',
'name'=>'ABC'
],
'1' =>
[
'id'=>'3',
'name'=>'DEF'
]
]
How can i achive key and value format in yii2?
You can fetch data as array like this:
$data = User::find()
->select('id, name')
->where(['id' => $id])
->orderBy('id DESC')
->asArray()
->all();
To create plain KEY => VALUE array use column() method:
$data = User::find()
->select(['name', 'id'])
->where(['id' => $id])
->orderBy('id DESC')
->asArray()
->indexBy('id')
->column();
First selected column [name] will be returned as a VALUE.

Cakephp 3 : How to give condition in get method?

I am trying to give a condition in cakephp 3 get method, where data will fetch by foreign id not primary key. Here I have tried below code:
$eventPasswordAll = $this->EventPasswordAll->get($id, [
'conditions' => ['event_id'=>$id],
'contain' => ['Events']
]);
But it showing me data according to id(primary key), not by event_id. How I add this condition in get methods like where event_id=my get id ?
Don't use get, use find. According to CakePHP 3.0 Table API, the get method:
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
You need to use find:
$eventPasswordAll = $this->EventPasswordAll->find('all', [ // or 'first'
'conditions' => ['event_id' => $id],
'contain' => ['Events']
]);
// or
$eventPasswordAll = $this->EventPasswordAll->find()
->where(['event_id' => $id])
->contain(['Events']);
Sometimes you want to get the id and the userid..
$this->loadModel('Jobapplications');
$application = $this->Jobapplications->find('all', [
'conditions' => ['id' => $id, 'user_id' => $user_id]
]);
$application = $application->first();

Saving records with a given uuid

I want to save a bunch of static records in my database with a given uuid, this is for testing purposes, so that on every system the application starts with the exact same dataset.
When inserting with SQL this is no problem but I wanted to use the CakePHP way ( I use a migrations file for this, but that does not matter).
The problem is that I give cake a data array like this and save it:
$data = [
['id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8', 'name' => 'test'],
['id' => 'c2bf879c-072c-51a4-83d8-edbf2d97e07e', 'name' => 'test2']
];
$table = TableRegistry::get('My_Model');
$entities = $table->newEntities($data, [
'accessibleFields' => ['*' => true],
'validate' => false
]);
array_map([$table, 'save'], $entities );
Everything saves, but all my items have been given a different uuid, If I debug a record after saving it shows the original uuid in the entity
'new' => false,
'accessible' => [
'*' => true
],
'properties' => [
'id' => '6b4524a8-4698-4297-84e5-5160f42f663b',
'name' => 'test',
],
'dirty' => [],
'original' => [
'id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8'
],
So why does cake generate a new uuid for me? and how do I prevent it
This doesn't work because primary keys are unconditionally being generated before the insert operation, see
https://github.com/cakephp/cakephp/blob/3.0.0/src/ORM/Table.php#L1486-L1490
// ...
$id = (array)$this->_newId($primary) + $keys;
$primary = array_combine($primary, $id);
$filteredKeys = array_filter($primary, 'strlen');
$data = $filteredKeys + $data;
// ...
$statement = $this->query()->insert(array_keys($data))
->values($data)
->execute();
// ...
Currently the UUID type is the only type that implements generating IDs, so providing custom IDs works with other types.
You can workaround this by for example overriding the _newId() method in your table so that it returns null, which effectively results in the existing primary key not being overwritten.
protected function _newId($primary)
{
// maybe add some conditional logic here
// in case you don't want to be required
// to always manually provide a primary
// key for your insert operations
return null;
}

Is the db in $this->db->last_insert() the class or the constant?

Since I am using 2 databases I have 2 separate config setups in config/database.php and load them in the Model's constructor with
$this->DB1 = $this->load->database('default', TRUE);
$this->DB2 = $this->load->database('reserve', TRUE);
I need to retrieve the id of the last inserted record and have used $this->db->last_insert();
and $this->DB2->last_insert();
but neither is working.
My insert query works fine and is
$insArray = array(
'propNumber' => $prp,
'fname' => $fname,
'lname' => $lname,
'unit' => $unit,
'email' => $email,
'NOC' => 0
);
$this->DB2->insert('users', $insArray);
$last_id = $this->db->last_insert();
$_SESSION['userID'] = $last_id;
return 'valid';
http://php.net/manual/en/function.mysql-insert-id.php
$last_id = $this->DB2->mysql_insert_id();

Resources