In CakePHP, it seems like a lot of functions can take their arguments as nested, multidimensional arrays, or as dotted strings:
$this->MyModel->contain(array(
'Something', 'Something.Else', 'Something.Else.Entirely'
));
$this->MyModel->contain(array(
'Something' => array(
'Else' => 'Entirely'
)
));
Therefore, I figure there must be a function somewhere in the core to switch from dotted to nested associative, but I can't find it for the life of me. Any ideas?
I've actually figured my own way to get this working leveraging the built-in Set functions.
Given:
$input = array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
);
This code will put that into a nested associative array.
$output = array();
foreach ($input as $key => $value) {
$output = Set::insert($output, $key, $value);
}
Here's the docs for Set::insert()
What you're looking for is Set::flatten(). It's not documented in the CakePHP manual, but take a look at the API definition.
It works something like this (the result might not be exact, this is from my head):
$array = array(
'Post' => array(
'id' => 1,
'title' => 'Some post title.',
'Tag' => array(
0 => array(
'id' => 4,
'name' => 'cakephp',
),
1 => array(
'id' => 7,
'name' => 'mysql',
),
),
);
);
$array = Set::flatten($array);
var_dump($array);
Your $array variable will now look like this:
Array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
)
It's just a convention throughout Cake, but each part does its own, customized parsing. If you look at the function ContainableBehavior::containments() in cake/libs/model/behaviors/containable.php, you'll see a lot of preg_matching and explode('.')ing going on. At least in the case of Containable, the verbose array('name' => array(...)) syntax seems to be the canonical syntax, but it can be abbreviated with the dot syntax, which will just be expanded. I'd guess that the expanding itself is just too varied among different parts to be easily summarized in a central function.
That, or they just haven't gotten to it yet. :)
Great question, I was just searching for the same thing. Apparently it's coming in Cake 2.2.
The new Hash class (a new, improved version of the Set class) has an expand() function which does this. You can view the code on Github if you need to use it in the meantime:
https://github.com/cakephp/cakephp/blob/2.2/lib/Cake/Utility/Hash.php
...However the solution nickf posted works great, too. :-)
Related
I am coverting my app over to cakephp 3.0 and I am having trouble finding an alternative to using neighbors in the find method.
I need to find the next record in the associated table and neighbors was a great way to do it.
//Open courses
$options = [
'conditions' => ['Employees.user_id' => 1, 'CoursesEmployees.completed' => false],
'limit' => 3,
'contain' => 'Employees'
];
$recentOpen = $this->CoursesEmployees->find('all', $options)->toArray();
// get next module for each open course
foreach ($recentOpen as $key => &$value) {
$currentModule = $value['CourseModule']['id'];
$neighbors = $this->CoursesEmployees->CourseModules->find(
'neighbors',
['field' => 'id', 'value' => $currentModule]
);
$value['CourseModule']['next_module'] = $neighbors['next']['CourseModule']['name'];
};
Another issue with the code I discovered is that $this->CoursesEmployees->find('all', $options)->toArray(); seems to return a complex array with everything cakephp uses to query the table and not the actual results like I got with cakephp 2. I added the ->toArray() as recommended with 3.0
Because I loathe "Answers" that simply point to a URL where you may or may not be able to decipher a half answer today, but could be gone tomorrow, here is my replacement custom finder:
// In src/Models/Table/ExampleTable.php
/**
* Find neighbors method
*/
public function findNeighbors(Query $query, array $options) {
$id = $options['id'];
$previous = $this->find()
->select('id')
->order(['id' => 'DESC'])
->where(['id <' => $id])
->first();
$next = $this->find()
->select('id')
->order(['id' => 'ASC'])
->where(['id >' => $id])
->first();
return ['prev' => $previous['id'], 'next' => $next['id']];
}
Called simply in the Controller:
// In src/Controller/ExamplesController.php
public function view($id = null) {
...
$neighbors = $this->Examples->find('neighbors', ['id' => $id]);
....
}
As explained here
there is no neighbors find method in cakephp 3.
But if you follow the flow of the issue you will find a custom finder to accomplish it, maybe it will work for you.
I'm having difficulty understanding the syntax of Hash::extract when dealing with HABTM.
I have data coming back from a find() that looks like this:
array(
(int) 0 => array(
'EventsGroup' => array(
'id' => '34',
'event_id' => '5',
'group_id' => '1'
)
),
(int) 1 => array(
'EventsGroup' => array(
'id' => '29',
'event_id' => '2',
'group_id' => '1'
)
)
)
I'm trying to get to an array that looks like: array(x,y,z) where x,y,z are event_id's.
The Cake documentation's example looks like:
$users = $this->User->find("all");
$results = Hash::extract($users, '{n}.User.id');
Based on that, I tried:
$eventsGroups = $this->EventsGroup->findAllByGroupId($groupid);
$secEvents = Hash::extract($eventsGroups, '{n}.{EventsGroup}.event_id' );
$secEvents2 = Hash::extract($eventsGroups, '{n}.EventsGroup.event_id' );
$secEvents3 = Hash::extract($eventsGroups, '{n}.[text=EventsGroup].event_id);
None of which worked.
I found a way to get what I wanted without using Hash::extract, but I'd like to use it as some of the other methods will be useful to me down the road.
Any help or pointers would be greatly appreciated!
Thanks
Have you tried:
$eventsGroups = $this->EventsGroup->findAllByGroupId($groupid);
$secEvents = Hash::extract($eventsGroups, '{n}.EventsGroup[event_id]' );
As the docs says to retrieve a field you should use a matcher and not a expression. And the brackets ({}) are not needed, they are used to build expressions like '{n}.{s}'...
Hi I'm currently working on a project and was wondering if it was possible to do two find functions in cakephp?
For example I am making a sports news website and I am grouping the news articles as top story, understory and headline.
What I want to do is retrive top stories so i can highlight these as the prominent story and then understory will be beneath as a lesser story and then headlines will be the least important.
This is what I have so far
function latestnews() {
$articles = $this->Article->find('all',
array('limit' =>3,
'order' =>
array('Article.date_created' => 'desc')));
if(isset($this->params['requested'])) {
return $articles;
}
$this->set('articles', $articles);
$articler = $this->Article->find('all',
array('Article.type' => 'topstory',
'Limit' => '1'
));
$this->set('articles', $articler);
}
however this doesn't seem to work, it doesn't limit the $articles function but instead echos all the data in the table.
in the view im doing a standard foreach statement to echo the data and I get thrown a undefined variable error.
Is what i am saying even possible or should I create different functions and then use them as elements?
Thanks for any input in advance!
You can bind the associationship with itself dynamically. Try this code:
function latestnews() {
$this->Article->bindModel(array('hasMany' => array('TopStory' => array('className' => 'Article',
'foreignKey' => false,
'conditions' => array('Article.type' => 'topstory')
),
'Highlight' .....
)));
$articles = $this->Article->find('all',
array('limit' =>3,
'order' => array('Article.date_created' => 'desc')));
if(isset($this->params['requested'])) {
return $articles;
}
$this->set('articles', $articles);
$articler = $this->Article->find('all',
array('Article.type' => 'topstory',
'Limit' => '1'
));
$this->set('articles', $articler);
}
Hope it will work for you.
#Arun Nope that didn't seem to work, I get this error, Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.type' in 'where clause' also I've tried to put it in an element with its own function and I then get thrown this error...
Notice (8): Undefined variable: data [APP/View/Elements/Articles/topstories.ctp, line 5]
Warning (2): Invalid argument supplied for foreach() [APP/View/Elements/Articles/topstories.ctp, line 5]
Notice (8): Undefined property: View::$Paginator [CORE/Cake/View/View.php, line 806]
Fatal error: Call to a member function prev() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/kickoff/app/View/Elements/Articles/topstories.ctp on line 21
The controller code is the following...
function topstories() {
$this->paginate = array(
'conditions' => array('Article.type' => 'topstory'),
'limit' => 2,
'order' => array(
'date_created' => 'asc'
)
);
$data = $this->paginate('Article');
$this->set(compact('data'));
}
I find this error confusing as if I don't put this in an element and in a view instead it works perfectly! however in an element not so perfect :S
any ideas as to why this is the case??
Instead of using two find methods in one function I instead chose to simply create different functions and use them as elements for example...
function premiershiptopstory() {
$pltopnews = $this->Article->find('all', array(
'conditions' => array('Article.league' => 'premiership',
'Article.type' => 'topstory')));
if(!empty($this->request->params['requested'])) {
return $pltopnews;}
$this->set('article', $pltopnews);
}
However in the view you must request the action otherwise you will get thrown an error, to request the action simply use this line of code...
<?php $pltopnews = $this->requestAction('/Articles/premiershiptopstory');
Hope this helps others!
So this is what I am trying to do.
My table say(Courses) has multiple entries with same id.
When I get the data from paginate it shows all the records. So if I have 3 records with Id 5 it will show record number 5 three times.
Now What I want is that it should show the record only once.
I searched online but can't find anything.
If anyone has come across such problem and found a solution to it please let me know.
Thanks,
I came across your problem, as I had a similar problem. David Z's solution did not work for me, but I did find that the group variable in $paginate worked for me.
So using your code sample above, this is how I'd think it should work.
$paginate = array(
'Courses' => array(
'limit' => 20,
'fields' => array('Courses.id'),
'conditions' => $cond,
'group' => array('Courses.id'),
'order' => array('Courses.id' => 'asc')
)
);
To hopefully shed some more light on the solution that worked for me, I have Systems that belong to Companies. I wanted to get a list of the unique companies, for the systems I have. This is the exact code I used, that worked for me
$this->paginate = array ('fields' => array ('Company.*'),
'order' => array('Company.name' => 'ASC'),
'group' => array('Company.id'));
$this->set('companies', $this->paginate($this->Company->System));
Hope this has helped
Looking at the CakePHP cookbook, the documentation for pagination shows that you can override the $paginate member. Behind the scenes, this similar to passing in the parameters for your model's find('all'). Maybe try setting parameter to explicitly return the filds that you are interested with the distinct keyword to narrow down the values you need?
class RecipesController extends AppController {
var $paginate = array(
'fields' => array('Model.field1', 'DISTINCT Model.field2')
);
}
So here is how my paginate variable looks like:
var $paginate = array(
'Courses' => array(
'limit' => 20,
'page' => 1,
'order' => array(
'Courses.id' => 'asc')
),
);
The condition variable looks something like this:
$cond = array("Courses.id LIKE "=>$this->data['id_search'],
"Courses.length LIKE "=>$this->data['length_search'],
"Courses.marks LIKE "=>$this->data['marks']
);
And this is how I am calling paginate.
$data = $this->paginate('CdmaRfReport',$cond);
I tried doing
$paginate = array(
'Courses' => array(
'limit' => 20,
'fields' => array('DISTINCT Courses.id'),
'page' => 1,
'conditions' => $cond,
'group' => array('id'),
'order' => array(
'Courses.id' => 'asc')
)
);
It doesn't seem to help.
I also tried
$cond = array("DISTINCT Courses.id "=>$this->data['id_search'],
"Courses.length LIKE "=>$this->data['length_search'],
"Courses.marks LIKE "=>$this->data['marks']
);
Even this errors out
I might be something wrong. But I am not able to figure it out.
Any suggestions please let me know.
I have been busy with the cakePHP framework for a couple of months now and I really love it. At the moment I'm working on a very new project and it does the job like it should (I think ...) but I feel uncomfortable with some code I wrote. In fact I should optimize my paginate conditions query so I get immediately the right results (right now I manipulate the result set by a bunch of Set::extract method calls.
I'll sketch the relevant aspects of the application. I have a model 'Site' who has a hasMany relationship with the model 'SiteMeta'. This last table looks as follow: id, site_id, key, value, created.
In this last model I record several values of the site at various periods. The name of the key I want to store (e.g. alexarank, google pagerank, ...), and off course also the value. At a given interval I let my app update this database so I can track evolution of this values.
Now my problem is this.
On the overview page of the various websites (controller => Sites, action => index) I'd like to show the CURRENT pagerank of the website. Thus I need one exact SiteMeta record where the 'created' field is the highest and the value in 'key' should be matching the word 'pagerank'. I've tried several things I read on the net but got none of them working (containable, bindmodel, etc.). Probably I'm doing something wrong.
Right now I get results like this when I do a $this->paginate
Array
(
[0] => Array
(
[Site] => Array
(
[id] => 1
[parent_id] => 0
[title] => test
[url] => http://www.test.com
[slug] => www_test_com
[keywords] => cpc,seo
[language_id] => 1
)
[SiteMeta] => Array
(
[0] => Array
(
[id] => 1
[site_id] => 1
[key] => pagerank
[value] => 5
[created] => 2010-08-03 00:00:00
)
[1] => Array
(
[id] => 2
[site_id] => 1
[key] => pagerank
[value] => 2
[created] => 2010-08-17 00:00:00
)
[2] => Array
(
[id] => 5
[site_id] => 1
[key] => alexa
[value] => 1900000
[created] => 2010-08-10 17:39:06
)
)
)
To get the pagerank I just loop through all the sites and manipulate this array I get. Next I filter the results with Set::extract. But this doens't feel quite right :)
$sitesToCheck = $this->paginate($this->_searchConditions($this->params));
foreach($sitesToCheck as $site) {
$pagerank = $this->_getPageRank($site['Site']);
$alexa = $this->_getAlexa($site['Site']);
$site['Site']['pagerank'] = $pagerank;
$sites[] = $site;
}
if (isset($this->params['named']['gpr']) && $this->params['named']['gpr']) {
$rank = explode('-', $this->params['named']['gpr']);
$min = $rank[0];$max = $rank[1];
$sites = Set::extract('/Site[pagerank<=' . $max . '][pagerank>=' . $min .']', $sites);
}
$this->set(compact('sites', 'direction'));
Could you guys please help me to think about a solution for this? Thanks in advance.
Thanks for the contributions. I tried these options (also something with bindmodel but not working also) but still can't get this to work like it should be. If I define this
$this->paginate = array(
'joins'=> array(
array(
'table'=>'site_metas',
'alias'=>'SiteMeta',
'type' =>'inner',
'conditions' =>array('Site.id = SiteMeta.site_id')
)
),
);
I get duplicate results
I have a site with 3 different SiteMeta records and a site with 2 different record.
The paginate method returns me 5 records in total. There's probably an easy solution for this, but I can't figure it out :)
Also I tried to write a sql query myself, but seems I can't use the pagination magic in that case. Query I'd like to imitate with pagination options and conditions is the following. The query returns exactly as I would like to get.
$sites = $this->Site->query('SELECT * FROM sites Site, site_metas SiteMeta WHERE SiteMeta.id = (select SiteMeta.id from site_metas SiteMeta WHERE Site.id = SiteMeta.site_id AND SiteMeta.key = \'pagerank\' order by created desc limit 0,1 )');
As you are trying to retrieve data in a hasMany relationship, cakephp doesn't join the tables by default. If you go for joins you can do something like:
$this->paginate = array(
'joins'=>array(
array(
'table'=>'accounts',
'alias'=>'Account',
'type' =>'inner',
'conditions' =>array('User.id = Account.user_id')
)
),
'conditions'=> array('OR' =>
array(
'Account.name'=>$this->params['named']['nickname'],
'User.id' => 5)
)
);
$users = $this->paginate();
$this->set('users',$users);
debug($users);
$this->render('/users/index');
You have to fit this according to your needs of course. More on joins, like already mentioned in another answer.
Edit 1: This is because you are missing the second 'conditions'. See my code snippet. The first 'conditions' just states where the join happens, whereas the second 'conditions' makes the actual selection.
Edit 2: Here some info on how to write conditions in order to select needed data. You may want to use the max function of your rdbms on column created in your refined condition.
Edit 3: Containable and joins should not be used together. Quoted from the manual: Using joins with Containable behavior could lead to some SQL errors (duplicate tables), so you need to use the joins method as an alternative for Containable if your main goal is to perform searches based on related data. Containable is best suited to restricting the amount of related data brought by a find statement. You have not tried my edit 2 yet, I think.
Edit 4: One possible solution could be to add a field last_updated to the table Sites. This field can then be used in the second conditions statement to compare with the SiteMeta.created value.
Try something like this:
$this->paginate = array(
'fields'=>array(
'Site.*',
'SiteMeta.*',
'MAX(SiteMeta.created) as last_date'
),
'group' => 'SiteMeta.key'
'conditions' => array(
'SiteMeta.key' => 'pagerank'
)
);
$data = $this->paginate('Site');
Or this:
$conditions = array(
'recursive' => 1,
'fields'=>array(
'Site.*',
'SiteMeta.*',
'MAX(SiteMeta.created) as last_date'
),
'group' => 'SiteMeta.key'
'conditions' => array(
'SiteMeta.key' => 'pagerank'
)
);
$data = $this->Site->find('all', $conditions);
If that does not work check this and this. I am 100% sure that it is possible to get the result you want with a single query.
Try something like this (with containable set up on your models):
$this->Site->recursive = -1;
$this->paginate = array(
'conditions' => array(
'Site.title' => 'title') //or whatever conditions you want... if any
'contain' => array(
'SiteMeta' => array(
'conditions' => array(
'SiteMeta.key' => 'pagerank'),
'limit' => 1,
'order' => 'SiteMeta.created DESC')));
I use containable so much that I actually have this in my app_model file so it applies to all models:
var $actsAs = array('Containable');
Many thinks to all who managed to help me through this :)
I got it fixed after all hehe.
Eventually this has been the trick for me
$this->paginate = array(
'joins'=> array(
array(
'table'=>'site_metas',
'alias'=>'SiteMeta',
'type' =>'inner',
'conditions' => array('Site.id = SiteMeta.site_id'))
),
'group' => 'Site.id',
'contain' => array(
'SiteMeta' => array(
'conditions' => array(
'SiteMeta.key' => 'pagerank'),
'limit' => 1,
'order' => SiteMeta.created DESC',
)));
$sites = $this->paginate();