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

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']
]);

Related

Unable to insert array into database

I am inserting multiple data from multiple forms into database but encounter an error at column photo
Unknown column 'Array' in 'field list'
Controller
if(!empty($_FILES['user_profile_file']['name'])){
$filesCount = count($_FILES['user_profile_file']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$studentImg = '';
$_FILES['userFile']['name'] = $_FILES['user_profile_file']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['user_profile_file']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['user_profile_file']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['user_profile_file']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['user_profile_file']['size'][$i];
$config['upload_path'] = FCPATH."uploadfiles/users/student-img";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 0;
$studentImgNew = uniqueId();
$config['file_name'] = $studentImgNew;
$this->load->library('upload', $config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$studentImg[$i]['photo'] = $fileData['file_name'];
$studentData[] = array(
'name' => $_POST['user_name'][$i],
'nric' => $_POST['user_nric'][$i],
'gender' => $_POST['user_gender'][$i],
'photo' => $studentImg,
'email' => $_POST['user_email'][$i],
'password' => md5($_POST['user_password'][$i]),
'is_active' => '0',
);
}
}
}
$this->User_account_model->create($studentData)
Model
function create($studentData){
foreach ($studentData as $key => $studentDatas) {
$insertStudentData[$key] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active'],
);
$this->db->insert('users_student', $insertStudentData[$key]);
}
if($this->db->affected_rows() != 1){
return false;
} else {
return true;
}
}
When I do print_r() I can get the exact data to be inserted into the database.
Array
(
[0] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e02cb962ac59075b964b07152d234b70
[name] => testing
[nric] => 123123
[gender] => 0
[photo] => Array
(
[0] => Array
(
[photo] => 5955cac09b8f71.jpg
)
)
[is_active] => 0
)
[1] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e13cc542ac59075b9643s5152d234g59
[name] => testing sister
[nric] => 123123
[gender] => 0
[photo] => Array
(
[0] => Array
(
[photo] => 5955cac09b8f72.jpg
)
)
[is_active] => 0
)
)
You are trying to insert an array inside the for insertStudentData[key].
Try This:
$insertStudentData[$key] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active']['0']['photo'],
);
$this->db->insert('users_student', $insertStudentData[$key]);
if you are trying to insert multiple rows, then you can use insert_batch
I have tried your code on my side and it gets perfectly correct. it added the multiple rows to the table. This is what I have done.
function create($studentData){
$insertStudentData = ''; //Create a Variable
foreach ($studentData => $studentDatas) {
$insertStudentData[] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo']['0']['photo'],
'is_active' => $studentDatas['is_active']
);
}
$this->db->insert_batch('users_student', $insertStudentData[$key]);
if($this->db->affected_rows() != 1){
return false;
} else {
return true;
}
}
Finally I solved my issue. From my controller I changed the assigning array like this :
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$studentImg[$i]['photo'] = $fileData['file_name'];
$studentData[] = array(
'name' => $_POST['user_name'][$i],
'nric' => $_POST['user_nric'][$i],
'gender' => $_POST['user_gender'][$i],
'photo' => $studentImg[$i]['photo'], // Edited row
'email' => $_POST['user_email'][$i],
'password' => md5($_POST['user_password'][$i]),
'is_active' => '0',
);
}
And my foreach model I changed to this :
foreach ($studentData as $studentDatas) {
$insertStudentData[] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active'],
);
}
$this->db->insert_batch('users_student', $insertStudentData);
And the output of those array :
Array
(
[0] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => 202cb962ac59075b964b07152d234b70
[name] => testing
[nric] => 123123
[gender] => 0
[photo] => 5955cac09b8f71.jpg
[is_active] => 0
)
[1] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e13cc542ac59075b9643s5152d234g59
[name] => testing sister
[nric] => 123123
[gender] => 0
[photo] => 5955cac09b8f72.jpg
[is_active] => 0
)
)
By the way, thank you for everyone that trying to help! I appreciate it.

How will i print the result in view in CodeIgniter?

I am trying to get a result in view returned as array in controller.This is a result of an api call using the json.
I need to display the results in the view. There is design integrated in view to display it.
How could i do it in CodeIgniter?
Function call:
$data['nearme_values'] = $this->swsdk->nearMe($lat, $lon, $radius, $page, $size);
This is the var_dumb result of the function call.
stdClass Object
( [content] => Array
( [0] => stdClass Object
( [id] => 1 [name] => Make America Great
[screenShotUrl] => http://52.77.190.221/SW/speaker_wire_images/streamSShot/stream-1479113014667.jpg
[type] => PUBLIC [status] => RECORDED [userId] => 1 [userHandle] => abhilekh
[channelId] => 1 [channelName] => Sports [likes] => 0 [views] => 0
[liveViewers] => 0
)
[1] => stdClass Object
( [id] => 2 [name] => Make America Great
[screenShotUrl] => http://52.77.190.221/SW/speaker_wire_images/streamSShot/stream-1479110563909.jpg
[type] => PUBLIC [status] => RECORDED [userId] => 1 [userHandle] => abhilekh
[channelId] => 2 [channelName] => Politics [likes] => 0 [views] => 0
[liveViewers] => 0
)
[2] => stdClass Object
( [id] => 3 [name] => Make America Great
[screenShotUrl] => http://52.77.190.221/SW/speaker_wire_images/streamSShot/stream-1479109601008.jpg
[type] => PUBLIC [status] => RECORDED [userId] => 2 [userHandle] => sudhanshu
[channelId] => 3 [channelName] => Fun [likes] => 0 [views] => 0
[liveViewers] => 0
)
[3] => stdClass Object
( [id] => 4 [name] => Make America Great
[screenShotUrl] => http://52.77.190.221/SW/speaker_wire_images/profiles/pic-130.jpg
[type] => PUBLIC [status] => RECORDED [userId] => 2 [userHandle] => sudhanshu
[channelId] => 4 [channelName] => Art [likes] => 0 [views] => 0
[liveViewers] => 0
)
) [last] => 1 [totalPages] => 1 [totalElements] => 4
[numberOfElements] => 4 [sort] => [first] => 1
[size] => 10 [number] => 0
)
I am new to the CodeIgniter. Please support with sample code.
if you are gonna call as API, no need to put in view.
Just echo like this in controller's method.
$nearme_values = $this->swsdk->nearMe($lat,$lon,$radius,$page,$size);
echo json_encode($nearme_values);
Displaying in View.
// in Controller.
$data['nearme_values'] = $this->swsdk->nearMe($lat, $lon, $radius, $page, $size);
$this->load->view('ur_view_file', $data);
// in view
foreach ($nearme_values->content as $nearme) {
echo $nearme->id .' / '. $nearme->screenShotUrl .' / '. $nearme->type .'<br>';
}

Facebook AdSet API "Your Budget is Too Low" error

Problem
I made a request to Facebook's Ad Set API attempting to create an ad set with the following JSON blob, and the error I received was "Your Budget Is Too Low. The minimum budget for this ad set is $32.04."
The ad set is set to use auto_bid and a valid lifetime_target. The ad set runs for 31 days, and with a $1 minimum daily budget, setting $64 for lifetime budget should've been sufficient.
Attempted Solutions
I tried to set a higher lifetime budget: from 64 to 1000 to 5000. 1000 did not work in this case, but 5000 did.
JSON Blob Used
Array
(
[account_id] =>
[adset_schedule] =>
[bid_amount] =>
[billing_event] => IMPRESSIONS
[budget_remaining] =>
[campaign_id] => 6054825216096
[created_time] =>
[creative_sequence] =>
[daily_budget] =>
[end_time] => 2016-11-08T07:59:59+0000
[id] =>
[is_autobid] => 1
[lifetime_budget] => 64
[lifetime_imps] =>
[name] => Some-Test-Campaign
[optimization_goal] => LINK_CLICKS
[pacing_type] =>
[recommendations] =>
[rf_prediction_id] =>
[start_time] => 2016-10-07T07:00:00+0000
[updated_time] =>
[targeting] => FacebookAds\Object\TargetingSpecs Object
(
[data:protected] => Array
(
[genders] =>
[age_min] =>
[age_max] =>
[geo_locations] => Array
(
[zips] => Array
(
[0] => Array
(
[key] => US:98004
)
[1] => Array
(
[key] => US:98005
)
[2] => Array
(
[key] => US:98006
)
[3] => Array
(
[key] => US:98007
)
[4] => Array
(
[key] => US:98008
)
[5] => Array
(
[key] => US:98009
)
[6] => Array
(
[key] => US:98011
)
[7] => Array
(
[key] => US:98014
)
[8] => Array
(
[key] => US:98015
)
[9] => Array
(
[key] => US:98019
)
[10] => Array
(
[key] => US:98021
)
)
)
[geo_markets] =>
[excluded_geo_locations] => Array
(
[countries] => Array
(
)
)
[exclusions] =>
[user_adclusters] =>
[interests] =>
[user_os] =>
[user_device] =>
[wireless_carrier] =>
[page_types] => Array
(
[0] => desktopfeed
[1] => mobilefeed
[2] => mobileexternal
[3] => rightcolumn
)
[connections] =>
[excluded_connections] =>
[family_statuses] =>
[friends_of_connections] =>
[flexible_spec] => Array
(
[0] => Array
(
[interests] => Array
(
[0] => Array
(
[id] => 6003277229371
)
)
[behaviors] => Array
(
[0] => Array
(
[id] => 6017447625983
)
)
)
)
[behaviors] =>
[relationship_statuses] =>
[interested_in] =>
[life_events] =>
[location_types] =>
[politics] =>
[markets] =>
[industries] =>
[income] =>
[net_worth] =>
[home_type] =>
[home_ownership] =>
[home_value] =>
[ethnic_affinity] =>
[generation] =>
[household_composition] =>
[moms] =>
[office_type] =>
[education_schools] =>
[education_statuses] =>
[college_years] =>
[education_majors] =>
[work_employers] =>
[work_positions] =>
[locales] =>
[zips] =>
[custom_audiences] =>
[custom_locations] =>
[excluded_custom_audiences] =>
[dynamic_audience_ids] =>
[product_audience_specs] =>
[excluded_product_audience_specs] =>
)
)
[promoted_object] =>
[adlabels] =>
[product_ad_behavior] =>
[execution_options] =>
[configured_status] =>
[effective_status] =>
)
I shortened the targeting for simplicity sake, but there's over 100 postal codes being targetd.
The solution here is that lifetime_budget is denoted in cents, so $64 should be 6400.
You may check if the budget you set is not less of required.
Perform this check at the endpoint:
https://graph.facebook.com/v2.12/act_{ads_account_id}/minimum_budgets
With headers:
Authorization: Bearer {your token with 'ads_management' rights to this account}
Returns:
{
"data": [
{
"currency": "AED",
"min_daily_budget_imp": 300,
"min_daily_budget_video_views": 300,
"min_daily_budget_high_freq": 750,
"min_daily_budget_low_freq": 6000
},
{
"currency": "ARS",
"min_daily_budget_imp": 400,
"min_daily_budget_video_views": 400,
"min_daily_budget_high_freq": 1000,
"min_daily_budget_low_freq": 8000
}
]
}
PS. I see, that my response is 2 years late, but someone may find it useful.

Get value from multi array?

This code
global $wpdb;
$bankaccountinfo = get_option( 'va_options' );
$arr = array($bankaccountinfo);
print_r(array_values($arr));
Provides me with the array below
Array
(
[0] => Array
(
[geocoder] => google
[geocoder_settings] => Array
(
[google] => Array
(
[geo_region] => us
[geo_language] => en
[geo_unit] => mi
[api_key] =>
)
)
[map_provider] => google
[map_provider_settings] => Array
(
[google] => Array
(
[geo_region] => us
[geo_language] => en
[geo_unit] => mi
[api_key] =>
)
)
[geo_unit] => mi
[currency_code] => EUR
[currency_identifier] => symbol
[currency_position] => left
[thousands_separator] => .
[decimal_separator] => ,
[tax_charge] => 21
[color] => blue
[admin_security] => manage_options
[wp_login] =>
[listing_price] => 0
[listing_charge] => no
[listing_duration] => 30
[moderate_listings] => no
[moderate_claimed_listings] => yes
[included_categories] => 0
[listings_per_page] => 10
[default_listing_sort] => default
[default_listing_home_sort] => default
[listings_featured_sort] => random
[editor_listing] => default
[default_geo_search_sort] => distance
[default_search_sort] => rating
[default_radius] =>
[addons] => Array
(
[featured-home] => Array
(
[enabled] => 1
[price] => 9.99
[duration] => 30
[period] => 30
[period_type] => D
)
[featured-cat] => Array
(
[enabled] => 1
[price] => 4.99
[duration] => 30
[period] => 30
[period_type] => D
)
)
[category_surcharges] => Array
(
[software] => Array
(
[surcharge] => 0
)
)
[categories_menu] => Array
(
[count] =>
[depth] => 3
[sub_num] => 3
[hide_empty] =>
)
[categories_dir] => Array
(
[count] =>
[depth] => 3
[sub_num] => 3
[hide_empty] =>
)
[events_enabled] =>
[default_event_geo_search_sort] => distance
[default_event_search_sort] => event_date
[default_event_radius] =>
[event_charge] => no
[event_price] => 0
[event_featured-home_enabled] => 1
[event_featured-home_price] => 0
[event_featured-cat_enabled] => 1
[event_featured-cat_price] => 0
[event_included_categories] => 0
[event_expiration] => 30
[moderate_events] => no
[events_per_page] => 10
[default_event_sort] => default
[default_event_home_sort] => default
[events_featured_sort] => random
[editor_event] => default
[listing_permalink] => fotografen
[edit_listing_permalink] => wijzigen
[renew_listing_permalink] => vernieuwen
[claim_listing_permalink] => claimen
[purchase_listing_permalink] => kopen
[listing_cat_permalink] => specialisme
[listing_tag_permalink] => zoekwoord
[event_permalink] => evenementen
[edit_event_permalink] => edit
[purchase_event_permalink] => purchase
[event_cat_permalink] => categorie
[event_tag_permalink] => zoekwoord
[event_day_permalink] => dag
[dashboard_events_permalink] => evenementen
[dashboard_event_comments_permalink] => reacties
[dashboard_event_favorites_permalink] => evenementen-favorieten
[dashboard_events_attending_permalink] => deelnemen
[dashboard_permalink] => dashboard
[dashboard_listings_permalink] => vermeldingen
[dashboard_claimed_permalink] => geclaimd
[dashboard_reviews_permalink] => beoordelingen
[dashboard_faves_permalink] => favorieten
[gateways] => Array
(
[enabled] => Array
(
[bank-transfer] => 1
[paypal] => 1
[pronamic_ideal] => 1
)
[bank-transfer] => Array
(
[message] => Bankinfo
)
[pronamic_ideal] => Array
(
[config_id] => 440
)
[paypal] => Array
(
[email_address] => *protected email*
[business_account] =>
[sandbox_enabled] =>
[pdt_enabled] =>
[pdt_key] => G9YvVFpThi0bNAu6wYQe4unz_ReqUttrcHWXHDvPA0pbdCQ3ky63CWFvGfu
[ipn_enabled] =>
)
)
[listing_sharethis] => 0
[event_sharethis] => 0
[blog_post_sharethis] => 0
[page_template_updates_1_2] => 1
[default_user_role_update_1_3_2] => 1
)
)
Now i would like to get and return the value of '[bank-transfer] => Array ( [message]' which is 'Bankinfo'. I am not sure how to do this with multiple (sub)arrays. Tried the code below which is not doing anything.
echo $arr['bank-transfer']['message'];
Can someone help me out?

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