How to create name value pair array in yii2 - arrays

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.

Related

register_graphql_field returning null values

I am trying to return values from a query that is only returning null values or is giving me errors based upon everything that I have tried. I have created a WP Plugin to put this code. I have pasted my code below
I have edited this code to what is currently working, but it is only giving me that last entry in the DB table. How would I get them all to display
function register_contact_form_fields() {
register_graphql_field( 'RootQuery', 'contactForm', [
'description' => __( 'Get a user submission', 'codmoncai-contact' ),
'type' => 'ContactForm',
'resolve' => function( $root, $args, $context, $info ) {
global $wpdb;
$combined_data = [];
$results = $wpdb->get_results("SELECT * FROM wpxd_contact_us");
}
return $data;
] );
}
By changing the 'type' in the register_graphql_field function to
'type' => [ 'list_of' => 'ContactForm' ],
Fixed my issue and allowed me to get all rows in the query

Select Distinc on cakephp 3 return wrong fields

this function should return the field of the table I want, but this doesn't happen, return all field of the table, with simply sql work fine "SELECT DISTINCT especie FROM packages"
public function listSpicies()
{
$packages = $this->Packages->find('all')
->select('especie')
->distinct('especie');
$this->set([
'success' => true,
'data' => $packages,
'_serialize' => ['success', 'data']
]);
}
I think You can use something like this:
$packages = $this->Packages->find('all' , [
'fields' => [
'anyAlias' => 'DISTINCT(espiece)'
]
])
->toArray();
Notice. If this collection is serialized and outputted as a JSON, check \App\Model\Entity\Package - if espiece is inside $_hidden array - remove this from array

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;
}

cakephp 3 show latest value with contain

i have a little problem with cakephp
i have DB
measurers => id, title, color...
usages => id, measurer_id, value...
and i want to do something like
$this->paginate = [
'contain' => [
'MeasurerTypes',
'Usages' => function($q) {
return $q->find('latest');
}
],
'finder' => ['my' => $this->user['id']]
];
$this->set('title',__('My measurers'));
$this->set('measurers', $this->paginate($this->Measurers));
$this->set('_serialize', ['measurers']);
this is only example code, is there to find only one latest variable and no all list for that?
Check this:
http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html#model-getinsertid
Example:
$lastItem = $this->YOURMODEL->getInsertID();
Edit:
In CakePHP 3
http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
$result = $articles->find('all')->all();
// Get the first and/or last result.
$row = $result->first();
$row = $result->last();

Resources