i want to get multiple rows value base on multiple id value and i m getting id in array.
id output array
pr($currentSessionData['Category']);
Array
(
[Category] => Array
(
[0] => 1
[1] => 24
[2] => 25
)
)
Below code for getting rows value but not working
$this->YourModelName->find('all', array(
'conditions' => array(
"YourModelName.id" => array($currentSessionData['Category'])
)
));
dont use array() .eg array($currentSessionData['Category'])
Try this.
$cat_ids=array(0=>10,1=>51,2=>51,3=>6561,4=>1,5=>561);
$this->YourModelName->find('all', array(
'conditions' => array(
"YourModelName.id" => cat_ids /*dont use array() */
)
));
i hope its helpful for you :)
Related
I am trying to get JSON(PHP) from PhpMyAdmin(Mysql). It actually need to look like:
[{ “converterno”: ”1”, “zoneno”: {“1a”, “codeid”:[“t1”,”t2”,”t3”]}, “zoneno”: {“1b”, “codeid”:[“t21”,”t0”,”t13”]}},{ “converterno”: ”2”, “zoneno”: {“2a”, “codeid”:[“t023”,”t9”,”t31”]}},………………………..
But what I am actually getting is
[{"converternumber":"1","zonenumber":{"0":"","codeid":["er"]}},{"converternumber":"1","zonenumber":{"0":"wr","codeid":["fxv"]}},{"converternumber":"2","zonenumber":{"0":"b2","codeid":["gffff"]}}]
And I don't know why I am getting Zero's at the starting
The PHP code is:
<?php
$db_name="app1";
$mysql_user="root";
$server_name="localhost";
$connectionn=mysqli_connect($server_name,$mysql_user,"",$db_name);
$n_converternumber= ["converternumber"];
$n_zonenumber= ["zonenumber"];
$n_codeid= ["codeid"];
$sql_query = "select * from addcode";
$result= mysqli_query($connectionn,$sql_query);
while ($row = mysqli_fetch_array($result)){
if(!isset($info[$row['converternumber']])){
$info[$row['converternumber']] = array(
'converternumber'=> $row['converternumber'],
'zonenumber' => array($row['zonenumber'],
'codeid' => array($row['codeid']))
);
}}
echo json_encode($info);
?>
Can anyone kindly tell me where I am going wrong in the "While" loop.
Went through all the code relating to JSON in StackOverFlow, but didn't find anything closer or similar. Tried almost everything and posting this now!!
Hope I would get any help here!
The table in the database is:
Table addcode
After extended discusson, you seem to desire a "grandparent-parent-child" structure. This is super easy to form and a completely associative structure will keep your data very compact and simple to iterate.
*and you should use mysqli_fetch_assoc() instead of the bloating mysqli_fetch_array() because you don't intend to use the indexed elements that it generates.
Code (Demo based on your database screenshot)
while ($row = mysqli_fetch_assoc($result)){
$info[$row['converternumber']][$row['zonenumber']][] = $row['codeid'];
}
The 3-level array would look like this:
array (
1 =>
array (
'1a' =>
array (
0 => 'test007',
1 => 'test006',
2 => 'test0094',
3 => 'test0098',
4 => 'test010',
5 => 'test111',
6 => 'test 008',
7 => 'test112',
8 => 'test004',
9 => 'test002',
10 => 'test001',
),
23 =>
array (
0 => 'rg',
),
'2a' =>
array (
0 => 'test001',
1 => 'test003',
),
'feh' =>
array (
0 => 'ndo',
),
'wr' =>
array (
0 => 'fxv',
),
),
2 =>
array (
'1a' =>
array (
0 => 'test',
),
'b2' =>
array (
0 => 'gffff',
),
),
)
Is there a way to format the $this->find('all') array into the $this->find('list') in the view? The reason I ask is so that I can pass that new array into the form helper options and then use the $this->find('all') array to build some additional things I need?
Array (
[0] => Array ( [School] => Array ( [id] => 0 [name] => Nature [address] => 112 Main [max_students] => 25 [application_level] => 5 ) )
[1] => Array ( [School] => Array ( [id] => 1 [name] => Math [address] => 112 Smith [max_students] => 25 [application_level] => 0 ) )
[2] => Array ( [School] => Array ( [id] => 2 [name] => Art [address] => 112 Lane [max_students] => 25 [application_level] => 0 ) )
)
So this is the array I get when I do a find('all'). I want to build the array so it looks like:
Array (
[0] => 'Nature'
[1] => 'Math'
[2] => 'Art'
)
This is usually done by the $this->find('list') function. Though the reason I want the whole array is because I need to add the application_level into $this->Form->input() function. This is because I need to add the option of class with the application level attached so I show only the shows with the application level based on the previous selection.
EDIT: Can't I just do $this->find('list', [insert parameters here?]);? I just don't understand how you set up the additional parameters?
If your query isn't overly complicated and isn't going to return a excessive number of results, just run it twice (once for find all and once for find list).
Find all, list, first, whatever are all the same in terms of the paramaters you pass in. E.g.:
$this->Model->find('all', array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'id ASC'
));
... you literally replace all with list. In your case, probably easiest to do it twice, once for each. Like this:
$parameters = array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'id ASC'
);
$alldata = $this->Model->find('all', $parameters);
$listdata = $this->Model->find('list', $parameters);
Otherwise, you can loop through it and populate your own list:
$list = array();
foreach($findall as $row) {
$id = $row['id'];
$name = $row['name'];
$list[$id] = $name;
}
$this->set('listdata', $list);
Short answer to your question is that there's no quick, easy way to select all and list from the same query, but you can re use your parameters (conditions, order etc) by passing them in as predefined arrays, or populate your own list.
An alternative answer to creating the results formatted like find('list') from results from find('all') using CakePHP's hash utility:
//where $data is the result of find all
App::uses('Hash', 'Utility');
$ids = Hash::format($data, array('{n}.Model.id'), '{0}'); //ids in an array.
$names = Hash::format($data, array('{n}.Model.name'), '{0}'); //names in an array
$dataAsList = array_combine($ids, $names);
To improve on kai's answer. The Hash class has a method called combine that can do what you're trying to do in only one line
$list = Hash::combine($data,'{n}.Model.id','{n}.Model.name');
the $list will be a flat array like data from find('list');
So I'm linking two of my models together and it's returning something like:
Array
(
[Submission] => Array
(
[id] => 47
[user_id] => 0
[title] => asdfasdfsa dfasdf asdfa sfa fadf
[source] => http://www.aol.com
[slug] =>
[category] => health
[created] => 2012-06-25 11:30:16
)
[User] => Array
(
[id] => 2
[username] => john
)
[SubmissionsVote] => Array
(
[0] => Array
(
[id] => 247
[user_id] => 2
[submission_id] => 47
[vote_type] => up
)
)
)
Sometimes, however, the number of votes will be from [0] - [n]. This is for my $newestSubmissions. The query I'm doing to give me that is:
public function newestSubmissions() {
$this->unBindModel(
array('hasMany' => array('Comment')));
return $this->find('all', array(
'fields' => array(
'Submission.id',
'Submission.user_id',
'Submission.title',
'Submission.source',
'Submission.slug',
'Submission.category',
'Submission.created',
'User.id',
'User.username'
),
'order' => 'Submission.created DESC'
));
}
What I'd like to do is to retrieve all votes throughout the $newestSubmissions array object as well as all of the votes (query below) on each of the $newestSubmissions to calculate the actual score so I can send a single array object called $newestSubmissions to my view, instead of $newestSubmissions and $submissionScore
public function getVoteType($userId, $submissionId) {
$voteType = $this->find('all', array(
'conditions' => array(
'User.id' => $userId,
'Submission.id' => $submissionId),
'fields' => array(
'SubmissionsVote.vote_type'),
'limit' => '1'
));
return $voteType[0]['SubmissionsVote']['vote_type'];
}
Basically I want to send a single score to my view along with all the other information in the array object instead of having to send an inner indexed array object within my parent array object (which is what I'm currently getting).
How can I do this?
OK... I tried to post this just as a comment, but it was too long. It's not really an answer as such.
Do you know about the containable behaviour? Check it out - it's good for determining what data you get back: http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Also, if you were to break your submissions vote table into two tables - upvotes and downvotes, then you could also use Cake's counterCache behaviour to keep track of the number of up/down votes directly in your 'submissions' table (you'd need to add upvote_count and downvote_count columns to your submissions table to do so).
This would make calculating submission score easier - and you wouldn't have to fetch all votes from the database to do it each time. For doco, search for counterCache on this page: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html It could be worth considering.
return $this->find('all', array(
'fields' => array(
'Submission.id',
'Submission.user_id',
'Submission.title',
'Submission.source',
'Submission.slug',
'Submission.category',
'Submission.created',
'User.id',
'User.username',
'submissionsvotes.vote_type'
),
'joins' => array(
array(
'table' => 'SubmissionsVote',
'alias' => 'submissionsvotes',
'type' => 'LEFT',
'conditions' => array
('User.id = SubmissionsVotes.user_id','Submission.id'=>'SubmissionsVotes.submission_id')
),
)
'group'=>'submissionsvotes.vote_type',
'order' => 'Submission.created DESC'
)
);
I'm using Set class of Cakephp to format the find returned array but cannot seem to find a way to get the counter starting at zero and auto-increment for array keys so it is like
[0] => 3
[1] => 6
[2] => 12
I'm currently using below query to get the data from my HasAndBelongsToMany table.
$interest_ids = Set::combine($this->User->Interestsub->find('threaded', array
(
'conditions' => array
(
'Interestsub.name' => $interests
),
//'fields' => array('Interestsub.id'),
'recursive' => -1
)
),
'{n}.Interestsub.id',
'{n}.Interestsub.id'
);
The reason why I need this is that I'm currently trying to get the returned array as part of bigger parent array preparing to be saved for SaveAll function. To be formatted properly, I need below nested array coming out:
[0] => Array
(
[interestssub_id] => 12
[user_id] => 2
)
[1] => Array
(
[interestssub_id] => 22
[user_id] => 2
)
[2] => Array
(
[interestssub_id] => 32
[user_id] => 2
)
Is there a way we can use Combine class to format the returned array like above?
There's no real reason to use the Set class in this case. Just use good old fashioned php:
$threaded = $this->User->Interestsub->find('threaded', array(
'conditions' => array(
'Interestsub.name' => $interests
),
'recursive' => -1
));
$interest_ids = array();
foreach ($threaded as $thread) {
$interest_ids[] = array(
'interestssub_id' => $thread['Interestsub.id'],
'interestssub_id' => $thread['Interestsub.user_id']
);
}
I have a scenario where i have templates which has many themes.
Clear enough that my relation will be template hasmany themes
I wanna show the template with number of themes and i am applying this code:
$this->Template->recursive = 2;
$this->Template->bindModel(
array(
'hasMany' =>array(
'TemplateTheme'=>array(
'className'=>'TemplateTheme',
'fields' => 'count(TemplateTheme.id) AS themes'
)
)
),false
);
$this->paginate = array(
'order' => array('Template.modified DESC'),
'limit' =>$limit
);
$template = $this->paginate('Template');
pr($template);die();
but i am getting is
Array
(
[0] => Array
(
[Template] => Array
(
[id] => 1
[name] => churchDesign
[status] => Active
[created] => 2011-10-24 10:37:23
[modified] => 2011-10-25 15:16:46
)
[TemplateTheme] => Array
(
[0] => Array
(
[template_id] => 1
[TemplateTheme] => Array
(
[0] => Array
(
[themes] => 3
)
)
)
)
)
[1] => Array
(
[Template] => Array
(
[id] => 2
[name] => blossoms
[status] => Active
[created] => 2011-10-19 00:00:00
[modified] => 2011-10-24 14:05:27
)
[TemplateTheme] => Array
(
)
)
)
The problem here is it is counting all the themes in first array(1st template).see [TemplateTheme] => Array
(
[0] => Array
(
[themes] => 3
)
the third theme actually belongs to the 2nd template.The relation is
template_id is in themes table to represent each theme for a template.
Template 1 has 2 themes and template 2nd has one theme and currently its showing all the three themes in the first template.
i want it like this way
templatename1
count of themes 1st template
template name 2
count of themes of 2nd template
Please tell me the right way to do this.
If you wanted to get the count of the Themes per each Template, the most elegant way is to use counterCache.
Another way is to use Containable behavior, which fetches only the related data which you wish, and then count the fetched data array in PHP.
After you attach the containable behavior to the Template model, some code like this should work:
$allTemplates = $this->Templates->find('all', array(
'contain' => 'TemplateTheme.name'
));
foreach($allTemplates as $template){
$currentThemeCount = count($template['TemplateTheme']);
foreach($template['TemplateTheme'] as $theme){
echo $theme['name'];
}
}
Hope this helps someone along the way.
you can count the themes array like
foreach($template as $t){
count($t['TemplateTheme'])
}
hope this helps
You should be using the find('count') method instead of using a virtual 'count' field like you're doing now. For example:
$allTemplates = $this->Template->find('all');
foreach($allTemplates as $data) {
$templateCount = $this->Template->TemplateTheme->find('count', array(
'conditions' => array(
'TemplateTheme.template_id' => $data['Template']['id']
)
));
// $templateCount should now contain the count of this specific template. Foreach will continue recursion for all others.
}