Cakephp Table query: SUM returning 0 - mysql

I'm having problems when using find to sum the field num_days from table events.
$events = TableRegistry::get('Events');
$query = $events->find('all')
->select(['used' => 'sum(num_days)'])
->first();
Why $query->used is always 0?
print_r($events->find('all')->select(['used' => 'sum(num_days)'])->toArray()) gives,
Array ( [0] => App\Model\Entity\Event Object ( [used] => 6 [[new]] => [[accessible]] => Array ( [*] => 1 ) [[dirty]] => Array ( ) [[original]] => Array ( ) [[virtual]] => Array ( ) [[errors]] => Array ( ) [[invalid]] => Array ( ) [[repository]] => Events ) )
6 is exactly the correct answer for the query and print_r shows it but $query->used is returning always 0.

try $query->order(['used' => 'DESC']); before $query->used
Also, we can add used as protected $_virtual = ['used']; inside Event.php Entity File

Related

Yii2 - Count and sum not include of result of ActiveQuery

Basically I have a legacy query in mysql that I will be implement into ActiveRecord,
Legacy Way, as expected
SELECT
a.container_seal,
a.size ,
count(a.size) as bundles,
sum(a.piece) as pieces
FROM pipe a
WHERE a.outgoing_pipe_id IS NULL
GROUP by a.container_seal, a.size
ORDER by a.container DESC
AR Way
$modelPipe = Pipe::find()
->select([
"container_seal",
"size",
"count(size) as bundles",
"sum(piece) as pieces"
])
->where(['outgoing_pipe_id' => NULL])
->groupBy(['container_seal', 'size'])
->orderBy(['container' => SORT_DESC])
->all();
But why, when I debug it,
<pre>
<?php
print_r($modelPipe);
?>
</pre>
The count and sum is not into.
Array
(
[0] => app\models\hanwa\Pipe Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[container_seal] => TEMU6099067/ EMCCSQ6566
[size] => 15 x 35 x 0.85 x 6000
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array
(
[container_seal] => TEMU6099067/ EMCCSQ6566
[size] => 15 x 35 x 0.85 x 6000
)
[_related:yii\db\BaseActiveRecord:private] => Array
(
)
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] => Array
(
)
)
[1] => app\models\hanwa\Pipe Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[container_seal] => TEMU6099067/ EMCCSQ6566
[size] => 35 x 35 x 0.75 x 6000
)
Is it Yii2 have another way to use sum and count in case 'select' ?
You shoudl add the pubblic var for bundles and pieces in your pipe model
(for recive the result of query )
class Pipe extends \yii\db\ActiveRecord
{
public $bundles;
public $pieces;
......

How to read youtube data api v3 response in php

I have following code:
$yt_profiles = $youtube->channels->listChannels('brandingSettings', array(
'mine' => 'true',
));
That returns the following output:
Google_Service_YouTube_ChannelListResponse Object
(
[collection_key:protected] => items
[etag] => "WFPuK6TsnblcGPcnMex79s42ynQ/sTnuE1bHO-tokx_mFFDt1ybN90g"
[eventId] =>
[itemsType:protected] => Google_Service_YouTube_Channel
[itemsDataType:protected] => array
[kind] => youtube#channelListResponse
[nextPageToken] =>
[pageInfoType:protected] => Google_Service_YouTube_PageInfo
[pageInfoDataType:protected] =>
[prevPageToken] =>
[tokenPaginationType:protected] => Google_Service_YouTube_TokenPagination
[tokenPaginationDataType:protected] =>
[visitorId] =>
[modelData:protected] => Array
(
[pageInfo] => Array
(
[totalResults] => 1
[resultsPerPage] => 1
)
[items] => Array
(
[0] => Array
(
[kind] => youtube#channel
[etag] => "WFPuK6TsnblcGPcnMex79s42ynQ/ecOcHFmWyWQ7ToCD7-B1L36b4L4"
[id] => UCQO6uXy5maTpYvSa_yM--Bw
[brandingSettings] => Array
(
[channel] => Array
(
[title] => Vasim Padhiyar
[showRelatedChannels] => 1
[featuredChannelsTitle] => Featured Channels
[featuredChannelsUrls] => Array
(
[0] => UCw-TnDmYDQyjnZ5qpVWUsSA
)
[profileColor] => #000000
)
[image] => Array
(
[bannerImageUrl] => http://s.ytimg.com/yts/img/channels/c4/default_banner-vfl7DRgTn.png
)
[hints] => Array
(
[0] => Array
(
[property] => channel.featured_tab.template.string
[value] => Everything
)
[1] => Array
(
[property] => channel.banner.image_height.int
[value] => 0
)
[2] => Array
(
[property] => channel.modules.show_comments.bool
[value] => True
)
)
)
)
)
)
[processed:protected] => Array
(
)
)
I want to loop through modelData:protected variable to get the list of channels and its items data. Its json object so $yt_profiles->modelData:protected not working while accessing. Please help me to solve this issue.
Thanks in advance
You can reach it as in an array:
print_r ($yt_profiles['modelData']);
Your request:
$yt_profiles = $youtube->channels->listChannels('brandingSettings', array(
'mine' => 'true',
));
To acces to values Channel title for example:
$titleChannel = $yt_profiles["items"][0]["brandingSettings"]["channel"]["title"];
To acces to values bannerImageUrl for example:
$banner = $yt_profiles["items"][0]["brandingSettings"]["image"]["bannerImageUrl"];
Does this help you?
$yt_profiles = $youtube->channels->listChannels('id, brandingSettings', array('mine' => 'true',));
foreach ($yt_profiles['modelData']['items'] as $searchResult) {
switch ($searchResult['kind']) {
case 'youtube#channel':
$channels[]= array('id'=> $searchResult['id'],
'brandingSettings'=> $searchResult['brandingSettings']);
break;
}
}

insert data into database from an embedded form in codeigniter

Hi I am using codeigniter and sheepIt clone forms.(embed forms).
I am trying to insert the data into database after submitting.
The output data is in this format when i used print_r()
Array
(
[project] => Array
(
[0] => Array
(
[module] => Design
[features] => Array
(
[feature_0] => Array
(
[feature] => Login
[Hours] => 10
)
[feature_1] => Array
(
[feature] => Signup
[Hours] => 10
)
)
)
[1] => Array
(
[module] => Development
[features] => Array
(
[feature_0] => Array
(
[feature] => Login
[Hours] => 20
)
)
)
)
[submit] => save
)
I can post the code of sheepIt forms also.
ANSWER:
$arr_data = $this->input->post();
foreach($arr_data['project'] as $prj) {
foreach($prj as $i) {
$arr['module'][] = module = $i['module'];
foreach($i['features'] as $f) {
$arr['feature'][] = $f['feature'];
$arr['Hours'][] = $f['Hours'];
}
}
}
print_r($arr);
Use this processed $arr data for storing or other.

DB Query in Drupal 7

I am trying to run a db query in drupal where, the content type has a node association field, and I am trying to get all notes of that type, where the NID of the current node matches any of the nodes specified in said note association field.
a visual example
Nodetype1
-- Node Association Field
NodeType2
I would like to get all Nodetype1's where Node Association Field matches the NID of Nodetype2 that is currently loaded.
My current db query is like so:
db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
and this returns nothing, when i know for a fact that such a node exists, I also tried dropping the WHERE statement and it returns an array like this:
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString] => SELECT * FROM field_data_field_promo_profile )
Any one have some ideas ?
db_query() returns an iterable object, so you just need to iterate over it:
$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
foreach ($result as $row) {
$entity_id = $row->entity_id;
// etc...
}
You should use parameters in your queries to prevent SQL injections.
For instance the query above should look like this:
$result = db_query("SELECT * FROM {field_data_field_promo_profile} p
WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid);
foreach ( $result as $row ) {
$entity_id = $row->entity_id;
// etc...
}

How to order sql results by counting a field in CakePHP 2.0

When I perform the following:
$popular_posts = $this->Blog->find('all', array('limit' => 5));
I get the following:
Array
(
[0] => Array
(
[Blog] => Array
(
[id] => 4fcfb37d-3eb0-4ec2-a744-175c987a2b72
[title] => This is a post example2
[short_description] => You've stumbled across our blog! Welcome! Here
[created] => 2012-06-06 21:46:05
[modified] => 2012-06-07 16:01:24
)
[Reply] => Array
(
[0] => Array
(
[id] => 4fcfb305-0c58-421b-9149-175c987a2b72
)
[1] => Array
(
[id] => 4fd0ae9e-dca0-4afe-862c-1258987a2b72
)
)
),
[1] ...
[2] ...
)
How can I order the results by the number of Reply ??? (desc)?
Try this
$data = $this->Blog->find('all',array('group' =>array('Reply.id'),
'order' => array('COUNT(Reply.id) DESC'),
'limit'=> 5));