Select from a table where associated table fieldname = 'x' in Cake PHP - cakephp

In CakePHP, I have two tables, Countries & Networks. They have a HABTM relationship and are joined by countries_networks.
I'm trying to get all countries from the countries table where the 'name' field in Networks = 'o2'
I've realised I can't do this using a basic find(), so I've been experimenting with the containable behaviour. I have managed to restrict the returned data, but it looks as though 'containable' doesn't exactly work as I want. Heres my code:
$countries = $this->Country->find('all', array('contain' => array(
'Network' => array(
'conditions' => array('Network.name =' => "o2"),
)
)));
This query however returns ALL countries, and the Network.name if its 'o2'. What I really need to do is return ONLY the countries that have a Network.name of 'o2', and no others.
Can anyone help? Thanks.

"=' =>"
What is it? there is no needed to use "=" symbol after "Network.name"

Your query returns you exactly what your ask.
Try to select from Network.
$countries = $this->Country->Network->find('first', array(
'conditions' => array('Network.name' => "o2"),
'contain' => array('Country')
));
$countries = $countries['Country'];

You should be able to do something like this:
$this->Country->hasAndBelongsToMany['Network']['conditions'] = array('Network.name'=>'o2');
$myCountries = $this->Country->find('all');
I haven't tested this, but it should get you pretty close to where you need to be.
Also, bear in mind that changing the hasAndBelongsToMany array like this will affect all subsequent queries against that model during the current page load (but it will be reset the next time the model is instantiated).

I'm on my way out the door, so sorry for the brief explanation.
I think what you want is a HABTM relationship, but to be able to filter based on the associated model's data. To do this, check out the "Containable" behavior in Cake's manual. Pretty sure that's what you're after.

Related

CakePHP Fulltext search MySQL with rating

I've read that, to be able to rank search results you may query MySQL like this:
SELECT * ,
MATCH (title, body) AGAINST ('$search') AS rating
FROM posts
WHERE MATCH (title, body) AGAINST ('$search')
ORDER BY rating DESC
Is there a way to do this in CakePHP 2.X?
Also, I need to do this while paginating at the same time. So I think I would need to write condition for the paginator, not a direct 'query'.
Thanks for your help!
Use like this it will prevent mysql injection too
array("MATCH(User.current_position) AGAINST(? IN BOOLEAN MODE)" => $srch_arr['text'])
Ok, it took me some time... Since, the key issue was to get a rating on the resulting matches, the complicated part in this query was the specific field:
MATCH (title, body) AGAINST ('$search') AS rating
I figured that I should just write that field in the "field" option, in the pagination array.
The resulting code was the following:
$this->paginate = array(
'limit' => 15,
'fields' => array('*', "MATCH (data) AGAINST ('$q') AS rating"),
'conditions' => "MATCH(SearchIndex.data) AGAINST('$q' IN BOOLEAN MODE)",
'order' => array(
'rating' => 'desc',
),
);
$paginatedResults = $this->paginate('SearchIndex');
And that worked seamlessly!
I think this is the best way to achieve real search results using Cake. Unless someone has a better alternative :)
Searching phrases in between double quotes will give you the results you should expect!
I have used the above database call by Thomas (thank you) and it does work seamlessly.
However the code:
'conditions' => "MATCH(SearchIndex.data) AGAINST('$q' IN BOOLEAN MODE)",
removes the Data Abstraction Layer and opens up your site to SQL injection.
It's probably not quite as good (haven't fully tested it) but try:
'SearchIndex.data LIKE'=>'%'.$search.'%'
I hope this is helpful in someway.

CakePHP find query across multiple datasources

I am tring to do the following:
My 'Company' Models are being stored in a 'default' datasource. In to
model I set the var $useDbConfig = 'default';
My 'User' Models are being stored in another datasource called
'users_db'. In this model I set the var $useDbConfig = 'users_db';
There is a 'belongsTo' relationship between 'Company' and 'User' models.
I want to do a recursive find query that brings back all users for each company in one go. I have the feeling that I cannot do this with Cake as it currently is.
When I try the following:
$res2 = $this->Company->find('all', array(
'conditions' => array('Company.id' => 1),
'recursive'=>2
));
I get a message that it cannot find the users table(its looking in the default source):
Error: Table user_groups for model User was not found in datasource default.
Is there any way I can do this?
Many thanks for any help you can provide.....
kSeudo.
Why not replace the your original statement by this:
$this->loadModel('User');
$res2 = $this->User->find('all',
array( 'conditions' => array( 'User.company_id' => 1 ) ));
This will produce the results you want.
Otherwise, if you wanted something tidier, you could add a fetch_users() function to your Company class that implemented a similar logic.
Ok, problem solved. Once I set the datasource in the model correctly everything seems to work fine.
Thanks guys

Cake HABTM Query, Order By Rand()

I'm aware that Cake HABTM associations are tricky at the best of times, but I seem to be making life even harder for myself...
If I want to return a random Item from the db, I can do it as follows in the Item model:
$random = $this->find('first', array(
'order' => 'rand()'
));
and if I want to find all the Items that are in a certain Category (where Item has a HABTM relationship to Categories), I know I can get a result set through $this->Categories->find.
My question is: how can I combine the two, so I can return a random Item that belongs to a specified Category? Is there any easy way? (If not, I'll gladly take any suggestions for a laborious way, as long as it works ;)
ETA: I can get some of the way with Containable, maybe: say I add the line
'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))),
then the Item results that I don't want come back with an empty Categories array, to distinguish them from "good" items. But really I don't want said Item results to be returned at all...
ETA(2): I can get a workaround going by unsetting my results in the afterFind if the Categories array is empty (thanks to http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering-results-returned-by-containable-behavior/ for the tip), and then having my random find function not give up until it gets a result:
while (!is_array($item)) {
$item = $this->random($cat);
}
but ugh, could this be any clunkier? Anyway, time for me to stop editing my question, and to go away and sleep on it instead!
Try this:
<?php
$this->Item->bindModel(array('hasOne' => array('ItemsCategory')));
$random = $this->Item->find('all', array(
'order' => 'rand()',
'conditions' => array('ItemsCategory.category_id' => '1')
));
?>

CakePHP AutoComplete Question

I am working on a book review application and I am using autoComplete to search for titles in when creating a review. The review model has an associated book_id field and the relationship is setup as the review hasOne book and a book hasMany reviews.
I am trying to pass the Book.id (into the book_id field), but I want to display Book.name for the user to select from. With the default setup (accomplished via CakePHP's tutorial), I can only pass Book.name. Is it possible to display the name and pass the id?
Also, I am passing it via the following code in the create() action of the review controller:
$this->data['Review']['book_id'] = $this->data['Book']['id'];
Is that the proper way to do it in CakePHP? I know in Ruby on Rails, it is automatic, but I can't seem to make it work automagically in CakePHP. Finally, I am not using the generator because it is not available in my shared hosting environment... so if this is the wrong way, what do I need other than associates in my models to make it happen automatically?
Thanks for the help and I promise this is my question for awhile...
UPDATE- I tried the following, but it is not working. Any ideas why?
function autoComplete() {
$this->set('books', $this->Book->find('all', array(
'conditions' => array(
'Book.name LIKE' => $this->data['Book']['name'].'%'
),
'fields' => array('id','name')
)));
$this->layout = 'ajax';
}
The problem is that when I use the code above in the controller, the form submits, but it doesn't save the record... No errors are also thrown, which is weird.
UPDATE2:
I have determine that the reason this isn't working is because the array types are different and you can't change the array type with the autoComplete helper. As a workaround, I tried the follow, but it isn't working. Can anyone offer guidance why?
function create() {
if($this->Review->create($this->data) && $this->Review->validates()) {
$this->data['Review']['user_id'] = $this->Session->read('Auth.User.id');
$this->Book->find('first', array('fields' => array('Book.id'), 'conditions' => array('Book.name' => $this->data['Book']['name'])));
$this->data['Review']['book_id'] = $this->Book->id;
$this->Review->save($this->data);
$this->redirect(array('action' => 'index'));
} else {
$errors = $this->Review->invalidFields();
}
}
FINAL UPDATE:
Ok, I found that the helper only takes the find(all) type or array and that the "id" field wasn't passing because it only applied to the autoComplete's LI list being generated. So, I used the observeField to obtain the information and then do a database lookup and tried to create a hidden field on the fly with the ID, but that didn't work. Finally, the observeField would only take the characters that I put in instead of what I clicked, due to an apparent Scriptaculous limitation. So, I ended up going to a dropdown box solution for now and may eventually look into something else. Thanks for all of the help anyway!
First of all, $this->data will only contain ['Book']['id'] if the field exists in the form (even if it's hidden).
To select something by name and return the id, use the list variant of the find method, viz:
$selectList = $this->Book->find('list', array(
'fields' => array(
'id',
'name'
)));
$this->set('selectList', $selectList);
In the view, you can now use $selectList for the options in the select element:
echo $form->input('Book.id', array('type' => 'hidden'));
echo $form->input('template_id', array(
'options' => $selectList,
'type' => 'select'
));

Forcing left join on my simple inner join query

The site is already built from years. I am doing some modifications to it. It has controllers "Posts" and "Topics". On the topics page all recent posts are displayed. So it is a simple find of posts from "Posts" table. The fetch is not all assiciated to topic as we are showing all "Posts" and not "Topic" specific "Posts". In Topics controller,
App::import('Model', 'Post'); and $Posts = new Post;
are added and I call the action "getDiscussions" from Model "Post". The problem is that though I am not using any left join with "Topics" and "Users" (which is one more model used to display user details with post), the query is adding Left joins with two tables and that is giving a wrong result.
Please help.
Many Thanks
Yukti
I think it is better to try to find out why cake is doing these "joins", rather than performing yet another forced query, so you might want to look into your model associations to check dependancies. Also, you can set $this->Posts->recursive = -1; to make sure you don't import unwanted stuff.
In the end, I am not sure what query you are trying to perform, so I can't help you further. However, here is a sample of a query I have successfully used to perform a left join, as I've noticed that many examples I found while writing my own were bugged:
$user_record = $this->User->find('first', array(
'conditions' => array('`Openidurl`.`openid`' => $openid),
'joins' => array(
array(
'table' => 'openidurls',
'alias' => 'Openidurl',
'type' => 'LEFT',
'foreignKey' => 'user_id',
'conditions'=> array('`Openidurl`.`user_id` = `User`.`id`')
)
)
)
);

Resources