Yii2 QueryBuilder union not working - yii2

Here is my code. I want to select results from two columns into one. Thanks.
$messages = (new \yii\db\Query())
->select(['idsender as idotherguy'])
->from('messages')
->where(['idreceiver' => Yii::$app->user->identity->id])
->all();
$messages2 = (new \yii\db\Query())
->select(['idreceiver as idotherguy'])
->from('messages')
->where(['idsender' => Yii::$app->user->identity->id])
->all();
$messages->union($messages2);
after advice here I also tried....
$messages = (new \yii\db\Query())
->select(['idsender as idotherguy'])
->from('messages')
->where(['idreceiver' => Yii::$app->user->identity->id]);
$messages2 = (new \yii\db\Query())
->select(['idreceiver '])
->from('messages')
->where(['idsender' => Yii::$app->user->identity->id]);
$messages->union($messages2);
$messages->all();
and i get query object
yii\db\Query Object
(
[select] => Array
(
[0] => idsender as idotherguy
)
[selectOption] =>
[distinct] =>
[from] => Array
(
[0] => messages
)
[groupBy] =>
[join] =>
[having] =>
[union] => Array
(
[0] => Array
(
[query] => yii\db\Query Object
(
[select] => Array
(
[0] => idreceiver as idotherguy
)
[selectOption] =>
[distinct] =>
[from] => Array
(
[0] => messages
)
[groupBy] =>
[join] =>
[having] =>
[union] =>
[params] => Array
(
)
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] =>
[where] => Array
(
[idsender] => 2
)
[limit] =>
[offset] =>
[orderBy] =>
[indexBy] =>
[emulateExecution] =>
)
[all] =>
)
)
[params] => Array
(
)
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] =>
[where] => Array
(
[idreceiver] => 2
)
[limit] =>
[offset] =>
[orderBy] =>
[indexBy] =>
[emulateExecution] =>
)
that is it... I tried also answe bellow and used in select 'idreceiver as idotherguy' ... but the result is the same

you should avoid the alias in united query , use literal select format and apply all to the result only
$messages = (new \yii\db\Query())
->select('idsender as idotherguy')
->from('messages')
->where(['idreceiver' => Yii::$app->user->identity->id]);
$messages2 = (new \yii\db\Query())
->select('idreceiver')
->from('messages')
->where(['idsender' => Yii::$app->user->identity->id]);
$messages->union($messages2);
$messages->all();
for see the result you should
foreach($messages as $key=> $value) {
echo $value->idotherguy;
}
or if the result is an array
foreach($messages as $key=> $value) {
echo $value['idotherguy'];
}
try check the ral sql code this way (instead of $messages->all();)
var_dump( $messages->createCommand()->sql);

Take a look at the documentation http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#union, you shouldn't have all() in your queries
$messages = (new \yii\db\Query())
->select(['idsender as idotherguy'])
->from('messages')
->where(['idreceiver' => Yii::$app->user->identity->id]);
$messages2 = (new \yii\db\Query())
->select(['idreceiver as idotherguy'])
->from('messages')
->where(['idsender' => Yii::$app->user->identity->id]);
$messages->union($messages2);
$messages->all();

I changed the code offered here like this and it works now fine....
$messages = (new \yii\db\Query())
->select(['idsender as idotherguy'])
->from('messages')
->where(['idreceiver' => Yii::$app->user->identity->id]);
$messages2 = (new \yii\db\Query())
->select(['idreceiver as idotherguy'])
->from('messages')
->where(['idsender' => Yii::$app->user->identity->id]);
$messages = $messages->union($messages2)
->all();
The result now is array with values as I wanted.
Array
(
[0] => Array
(
[idotherguy] => 3
)
[1] => Array
(
[idotherguy] => 11
)
[2] => Array
(
[idotherguy] => 10
)
)
Thanks for help boys :)

Related

CakePHP 3 - Model - Accessing data from third layer of array

CakePHP 3
My Model
Users has Many Badges
Titles has Many Badges
Badges belongs to Titles
Badges belongs to Users
In my Users View, I want to access the value of Titles but I don't know how.
**Users Controller**
public function view($id = null)
{
$this->viewBuilder()->layout('admin');
TableRegistry::get('Users');
$user = $this->Users->get($id, [
'contain' => ['Badges', 'Projects', 'Reports', 'Rewards']
]);
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
UsersTable.php
$this->hasMany('Badges', [
'foreignKey' => 'user_id'
]);
TitleTable.php
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Titles', [
'foreignKey' => 'title_id',
'joinType' => 'INNER'
]);
BadgesTable.php
$this->hasMany('Badges', [
'foreignKey' => 'title_id'
]);
App\Model\Entity\User Object
(
[id] => 1
[firstname] => Jl
[lastname] => C
[email] => m
[username] => admin
[password] =>
[profile_pic] => /img/noimage.jpg
[report_count] => 0
[role] => admin
[reputation] => 999999
[account_status] => Active
[confirmation] => 1
[site_name] => C
[site_email] => mi
[created] => Cake\I18n\FrozenTime Object
(
[time] => 2017-02-27T13:46:51+08:00
[timezone] => Asia/Manila
[fixedNowTime] =>
)
[modified] => Cake\I18n\FrozenTime Object
(
[time] => 2017-03-01T10:37:50+08:00
[timezone] => Asia/Manila
[fixedNowTime] =>
)
[badges] => Array
(
[0] => App\Model\Entity\Badge Object
(
[id] => 1
[user_id] => 1
[title_id] => 11
[created] => Cake\I18n\FrozenTime Object
(
[time] => 2017-02-28T15:16:08+08:00
[timezone] => Asia/Manila
[fixedNowTime] =>
)
[modified] => Cake\I18n\FrozenTime Object
(
[time] => 2017-02-28T15:16:08+08:00
[timezone] => Asia/Manila
[fixedNowTime] =>
)
[[new]] =>
[[accessible]] => Array
(
[*] => 1
)
[[dirty]] => Array
(
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[invalid]] => Array
(
)
[[repository]] => Badges
)
)
[[new]] =>
[[accessible]] => Array
(
[*] => 1
)
[[repository]] => Users
)
What I want is to get the data from title table (i.e name)
[badges] => Array
(
[0] => App\Model\Entity\Badge Object
(
[id] => 1
[user_id] => 1
[title_id] => 11
[created] => Cake\I18n\FrozenTime Object
In your contain, you can use 'Model.Model' to get further related data like so :
$user = $this->Users->get($id, [
'contain' => ['Badges.Titles', 'Projects', 'Reports', 'Rewards']
]);

insert array data to mysql codeigniter 3

How can I insert array data to mysql using code igniter ??
I tried example from CI documentation like this
$data = array(
'id_kls' => 'id_kls',
'fk__id_kls' => 'fk__id_kls',
'id_reg_pd' => 'id_reg_pd',
'nm_pd' => 'nm_pd',
'asal_data' => 'asal_data',
'nilai_angka' => 'nilai_angka',
'nilai_huruf' => 'nilai_huruf',
'nilai_indeks' => 'nilai_indeks',
);
$this->db->insert('master_nilai', $data);
// Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
But not working ..
I have array data like this
Array
(
[error_code] => 0
[error_desc] =>
[result] => Array
(
[0] => Array
(
[id_kls] => f77294f7-2a5a-4876-860b-824d227d5b19
[fk__id_kls] => 02
[id_reg_pd] => 001be76b-4e58-4cea-96cf-fee2d8e0abdc
[nm_pd] => SUYATNO
[asal_data] => 9
[nilai_angka] =>
[nilai_huruf] => B
[nilai_indeks] => 3.00
)
Make sure you've enable config/autoload.php/$autoload['libraries'] = array('database');
and config/database.php/your hostname,username,dbname!

How to get the first row of a result in Yii2? (queryRow Equivalent)

how can i get the first row of result? Below is my code which is giving me an error like this Undefined index: module
if ( substr( $action, 0, 4 ) === "stl_" )
{
$query = "SELECT * FROM a_actions LEFT JOIN a_modules ON ( a_modules.id=a_actions.module_id )
WHERE a_actions.id=(SELECT dependency FROM a_actions WHERE action='{$action}') AND a_modules.module_status = 1 ";
$action = \Yii::$app->db->createCommand( $query )
->queryAll();
//print_r($action);die();
$module = $action[ 'module' ];
$action = $action[ 'action' ];
}
$action has value
Array ( [0] => Array ( [id] => 7 [module_id] => 7 [action] => index [label] => Members [dependency] => [created_by] => [created_at] => [updated_by] => [updated_at] => [is_deleted] => 0 [module] => members [module_name] => [module_status] => 1 ) )
in Yii1 i would have used
$action = \Yii::$app->db->createCommand( $query )
->queryRow();
You can use queryOne()
\Yii::$app->db->createCommand( $query )
->queryOne();
QueryOne()

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

CakePHP multiple nested query

I want my query as:
$conditions = array(
'ManageTrackby.trackby_num NOT LIKE' => '%n/a%',
'Balancesheet.subscriber_id' => $_SESSION['Auth']['User']['subscriber_id'],
'Balancesheet.show_id' => $this->Session->read('openshowid'),
'OR' => array('Balancesheet.season_id' => $season_id, 'Balancesheet.season_id is null'),
'OR' => array('Balancesheet.episode_id'=> $episode_id, 'Balancesheet.episode_id is null')
);
which skips last OR option here and giving below result:
Array
(
[ManageTrackby.trackby_num NOT LIKE] => %n/a%
[Balancesheet.subscriber_id] => 105
[Balancesheet.show_id] => 56
[OR] => Array
(
[Balancesheet.episode_id] => 86
[0] => Balancesheet.episode_id is null
)
)
Here, it misses SEASON_ID from the condition, any idea why?
Please guide me !
Try this. If you want all the first conditions, plus an or of the second conditions, then you will want the OR within the AND array. For complex finds, look up the info on this page http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
$conditions = array(
'AND' => array(
'ManageTrackby.trackby_num NOT LIKE' => '%n/a%',
'Balancesheet.subscriber_id' => $_SESSION['Auth']['User']['subscriber_id'],
'Balancesheet.show_id' => $this->Session->read('openshowid')
)
'OR' => array(
array('Balancesheet.season_id' => $season_id, 'Balancesheet.season_id is null'),
array('Balancesheet.episode_id'=> $episode_id, 'Balancesheet.episode_id is null')
)
)
Your array is setting the OR element twice. Put the two OR statements in their own individual array:
$conditions = array(
'ManageTrackby.trackby_num NOT LIKE' => '%n/a%',
'Balancesheet.subscriber_id' => $_SESSION['Auth']['User']['subscriber_id'],
'Balancesheet.show_id' => $this->Session->read('openshowid'),
array('OR' => array('Balancesheet.season_id' => $season_id, 'Balancesheet.season_id is null')),
array('OR' => array('Balancesheet.episode_id'=> $episode_id, 'Balancesheet.episode_id is null'))
);