Select Distinc on cakephp 3 return wrong fields - cakephp

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

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

How to get contain clause to generate the correct code in CakePHP

I have the following code in a Table definition.
$paginationQuery = $this->find()
->select([
'Members__id','Members__member_type','Members__first_name',
'Members__middle_name','Members__last_name','Members__suffix'
])
->contain([
'SocialMembers' => [
'foreignKey' => false,
'queryBuilder' => function (Query $q) {
return $q->where([
'Members.Members__id' => 'SocialMembers.full_member_id'
]);
}
]
])
->from([
$this->getAlias() => $query
])
->order([
'Members__last_name' => 'ASC',
'Members__first_name' => 'ASC'
]);
return $paginationQuery;
This is to paginate the results of a union of two sets of extracted data.
The problem comes from the queryBuilder function. The left join that is generated looks like this:
LEFT JOIN members SocialMembers ON (
SocialMembers.member_type = 2
AND Members.Members__id = 'SocialMembers.full_member_id'
)
There is an unneeded pair of single quotes around SocialMembers.full_member_id. queryBuilder appears to correctly handle the Members.Members__id, but not the value field of the array. Is there any way to get this to generate correctly?
Was able to resolve this by moving the contains clause to the preceding finder methods.

Count in contain Cakephp 3

I have a table Post and this has a has-many association with a table Stars.
I can get all the associated data using:
$this->Posts->find()->contain(['Stars']);
That works well.
But I want to count the Stars. I have tried this but its not working:
$this->Posts->find->contain([
'Stars' => function($q) {
return $q->select(['total' => $q->func()->count('Stars.post_id')]);
}
]);
//I've also tried this
...
...$q->select(['total' => "COUNT(Stars.post_id)"]);
...
//Also fail
This does not return the number of associated Stars.
Is there something wrong or should do it some other way?
Thanks
you have to select also the foreign key otherwise cake is not able to join the tables. And you have also to group the result
'Stars' => function($q) {
$q->select([
'Stars.post_id',
'total' => $q->func()->count('Stars.post_id')
])
->group(['Stars.post_id']);
return $q;
}
As here we have used total as virtual field, can be create more like this in same model as:
public function index()
{
$checklist = TableRegistry::get('Checklists');
$query = $checklist->find()
->where('Checklists.is_deleted = 0')
->contain([
'ChecklistTitles' => function($q) {
return $q -> select([
'ChecklistTitles.title',
'ChecklistTitles.checklist_id'
]);
},
'ChecklistTypes' => function($w){
return $w->select(['ChecklistTypes.type']);
},
'AssignedChecklists' => function($e){
$e->select([
'AssignedChecklists.checklist_id',
'completed' => $e->func()
->count('AssignedChecklists.checklist_id'),
])
->group(['AssignedChecklists.checklist_id'])
->where(['AssignedChecklists.is_deleted = 0 AND AssignedChecklists.checklist_status = 2']);
return $e;
}
]);
// ->toArray();
// pr($query);die;
$this->paginate = [
'limit' => 20,
'sortWhitelist' => [
'id', 'checklist_title', 'checklist_type'
]
];
$this->set('query', $this->paginate($query));
$this->set(compact('checklists','query'));
$this->set('_serialize', ['checklists','query']);
}
As here I have calculated completed, I want to calculate cancelled with different where condition, what will be the syntax for it in cakephp3?
Try this:
$total = $this->Posts->find()->contain(['Stars'])->count();
As refereed in the cookbook.

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