cakephp convert custom query to cakephp query - mysql

I have the following code in my projects controller's index action
I achieved it via custom queries
1- it is good to use custom queries?
2- how can I write the following queries using cakephp functions joins contains etc
3- which method will be good?
my tables are as below
portfolio_projects [id,name,....,user_id,job_id,manymore_id]
portfolio_images [id,project_id,image,orders,status,.....]
portfolio_tags [id,tag,....]
portfolio_project_tags[id,project_id,tag_id]
and query is as below. I did this to fetch only needed data that is projects with its images and tags but not project's (user,job and others)
there are other tables linked to tags, images tables too but I do not need that data here.
$this->Project->recursive = -1;
$projects = $this->Project->find('all',array(
'conditions' => array(
'Project.user_id' => $this->Auth->user('id')
)
));
foreach($projects as $key=>$project)
{
//fetching project related tags starts here
$q="select * from portfolio_project_tags where 0";
$q="select tag.id as id,tag.tag from portfolio_project_tags as p left outer join portfolio_tags as tag on p.tag_id=tag.id where p.project_id=".$project['Project']['id'];
$tags = $this->Project->query($q);
$projects[$key]['Project']['tags']=$tags;
//fetching project related tags ends here
//fetching project related images starts here
$q2="select * from portfolio_images where 0";
$q2="select img.id as id,img.title as title, img.image as image from portfolio_images as img where img.project_id=".$project['Project']['id']." and img.status='Publish' order by orders";
$snaps = $this->Project->query($q2);
$projects[$key]['Project']['snaps']=$snaps;
//fetching project related images ends here
}
$this->set('projects',$projects);

You have 3 possibilities (at least) to retrieve data from a join table in CakePHP, that you should consider in the following order:
Containable Behaviour
CakePHP join query
Custom query
In your example, only the q1 request need a join because the q2 can be express as:
$this->PorfolioImage->find('all', array(
'fields' => array('PortfolioImage.id, PortfolioImage.title, PortfolioImage.image'),
'conditions' => array(
'PortfolioImage.project_id' => $project['Project']['id']
)
));
The containable behaviour
In your Project model, you could add information to the related models, such as:
class Model extends AppModel {
public $actAs = array('Containable');
public $hasMany = array('PortfolioImage');
public $belongsTo = array('PortfolioTag') ;
}
Then, when you retrieve a Project, you have access to the related PortfolioImage and Tag, for example:
debug($this->Project->read(null, 1)) ;
Would output:
Array(
'Project' => array(
'id' => 1,
/* other fields */
),
'PortfolioTag' => array(
'id' => /* */,
'tag' => /* */
),
'PortfolioImage' => array(
0 => array(
'id' => /* */,
/* other fields */
),
1 => array(/* */)
)
)
You just need to be carefull on the naming of foreign key, the CakePHP documentation about relationship is really easy to read.
CakePHP join query
You can do a join query in CakePHP find method:
$this->Project->find('first', array(
'fields' => array('Tag.id', 'Tag.title'),
'joins' => array(
'table' => 'portfolio_tags,
'alias' => 'PortfolioTag',
'type' => 'LEFT OUTER',
'conditions' => array('PortfolioTag.id = Project.tag_id')
)
)) ;
I'm really not used to CakePHP join queries (the Containable behaviour is often sufficient), but you'll find lot of information in the CakePHP documentation.
Custom queries
You should really not use custom queries except if you really know what you're doing because you have to take query of almost anything (sql injection at first place). At least, when doing custom queries, use Prepared Statements (see information at the end of this link).

Related

In the controller do a find specifiing basic conditions but the query built by cakephp doesn't match the conditions

In the controller :
$budget = $this->Budget->find('first',
array('conditions' => array(
"copros_id" => $this->Session->read('Copro.id'),
"typebudgets_id" => $typebudget['Typebudget']['id'],
"exercices_id" => $this->Session->read('Exercice.id'))));
generates the sql:
SELECT `Budget`.`id`,
`Budget`.`created`,
`Budget`.`modified`,
`Budget`.`title`,
`Budget`.`statusbudgets_id`,
`Budget`.`typebudgets_id`,
`Budget`.`copros_id`,
`Budget`.`visible`,
`Budget`.`exercices_id`
FROM `default_schema`.`budgets` AS `Budget`
WHERE `Budget`.`typebudgets_id` = ('466b50a5-4736-11e6-a160-00163ee3b504')
The Model contains :
public $belongsTo = array(
'StatusBudget' => array(
'className' => 'StatusBudget',
'foreignKey' => 'statusbudgets_id'
),
'Exercice' => array(
'className' => 'Exercice',
'foreignKey' => 'exercices_id'
),
'Typebudget' => array(
'className' => 'Typebudget',
'foreignKey' => 'typebudgets_id'
),
'Copro' => array(
'className' => 'Copro',
'foreignKey' => 'copros_id'
),
);
It looks like the conditions in the find are ignored by cakephp (2) when building the query; specifying different conditions in the find give the same sql as a result. As if the conditions don't matter in fact.
Strange (for me).
Thanks
A couple of things may be happening here:
First try to clear the model cache. If you don't know how to use the cake console just delete the files in the /tmp/cache/model folders.
The table behind the Budget model does NOT have the columns you are making a reference to. Or there is a typo in their name. In that case Cake will not use them when you build your conditions.
The db table for budget has all the required columns, but the way the Table class is defined could interfere with properly reading the table structure from the database.
Thinking about Ilia Pandia's answer I tried to specify more precisly my conditions:
$budget = $this->Budget->find('first',
array('conditions' => array(
"Budget.copros_id" => $this->Session->read('Copro.id'),
"Budget.typebudgets_id" => $typebudget['Typebudget']['id'],
"Budget.exercices_id" => $this->Session>read('Exercice.id'))));
The sql generated is now what I expected:
SELECT `Budget`.`id`, ...
FROM `default_schema`.`budgets` AS `Budget`
LEFT JOIN `default_schema`.`status_budgets` AS `StatusBudget` ON (`Budget`.`statusbudgets_id` = `StatusBudget`.`id`)
LEFT JOIN `default_schema`.`exercices` AS `Exercice` ON (`Budget`.`exercices_id` = `Exercice`.`id`)
LEFT JOIN `default_schema`.`typebudgets` AS `Typebudget` ON (`Budget`.`typebudgets_id` = `Typebudget`.`id`)
LEFT JOIN `default_schema`.`copros` AS `Copro` ON (`Budget`.`copros_id` = `Copro`.`id`)
WHERE Budget.copros_id = '5af2bda8-97d0-403a-ad96-4cf1ac171864'
AND Budget.typebudgets_id = '466b50a5-4736-11e6-a160-00163ee3b504'
AND Budget.exercices_id = '5af2c13b-43d0-412f-97d9-4752ac171864' LIMIT 1
Thank you!

CakePHP 2.3: Conditionally retrieve unique model information based on another model's use of it

I'm trying to create an AJAX form whereby the content of a select field populates based on the choice of a preceding select field (you see this a lot with 'country' populating 'state/province'). In my case, I want users to be able to choose their province only if active accounts exist in it.
The Javascript I can write no problem. Fetching the data is where I'm... not so much stuck as doing too much work. CakePHP likes to build select fields with options in an array of the form
$options = array(select_option_value => display_text)
My strategy, though functional, must be more convoluted than cake intended (this a is segment of a controller method).
$provinceData = $this->Account->find('all',array('recursive' => 0,
'joins' => array(
array(
'table' => 'provinces',
'type' => 'LEFT',
'conditions' => array('Account.province_id = provinces.id')
)),
'fields'=>array('provinces.id', 'provinces.name', 'provinces.abbrev'),
'conditions' => array('registration > 2')));
$provinces = array();
foreach($provinceData as $pd) {
/*note: lowercase, plural below b/c can't get 'alias' => 'Province'
to work in joins array above : ( */
$id = $pd['provinces']['id'];
$name = $pd['provinces']['name'];
$provinces[$id] = $name;
}
$this->set(compact('provinces'));
Can anyone point out a more appropriate way to do this? I assume there must be a MySQL query that can do this, but I'm pretty bad at writing elaborate MySQL queries in the first place, let alone via Cake's convention (and, for you MySQL gurus out there, I'm happy to do this from a Model->query(//MySQL code) call instead!
Any and all help truly appreciated.
Assuming the relationship Account belongsTo Province you can try this code:
$accounts = $this->Account->find(
'all',
array(
'fields' => array('Account.province_id', 'Province.name'),
'conditions' => array('Account.registration > 2'),
'group' => 'Account.province_id'
)
);
$provinces = Hash::combine($accounts, '{n}.Account.province_id', '{n}.Province.name');
$this->set(compact('provinces'));
edit: missed bracket and a period instead of an underscore . Now should work

CakePHP2.3: Building complex conditional Model->find() options

I'm not savvy with MySQL or databases generally, so here's a model of my data (table{cols}]) in order to make my question coherent:
Domains{id, name} Note: 'domains' here does not refer to web domains
Subdomains{id, domain_id, name}
Items{id, subdomain_id, name}
SubdomainsItems{id, subdomain_id, item_id} no domain_id column!
My Items Controller has a function, fetchWithin($domains, $subdomains) which, ultimately, should just execute one of two complexish find(). It's the complexish I can't get past.
Programmatically I can achieve this, but I'm quite certain the better way is by clever joins and the like. Alas, currently this is approach:
If $domainsis empty, do only steps 2&3, otherwise:
foreach($domains as $d): get all the rows of Subdomains where Subdomain.domain_id = Domains.id as $subdomains
foreach($subdomains as $s) : go get all the rows of SubdomainsItems where SubdomainsItems.subdomain_id = Subdomains.id as $item_ids
foreach($items_ids as $i): get all the rows of Items where Items.id = SubdomainsItems.items_id
This works, but I think this is obviating the power of a relational database and I'd like to understand how this should be done (ie. according to either Cakephp convention or simply by whatever MySQL statement would achieve this).
Help would be hugely appreciated, I try to learn the more complex aspects of SQL but it just goes right over my head. :S
Understanding the necessary query
With the structure described in the question the kind of query necessary is of the form:
SELECT
*
FROM
items
LEFT JOIN
subdomains ON (
items.subdomain_id = subdomains.id
)
LEFT JOIN
domains ON (
subdomains.domain_id = domains.id
)
WHERE
domains.name = "foo"
AND
subdomains.name IN ('some', 'list', 'of', 'subdomains');
Compared to the logic in the question this joins all three tables together and permits finding all items by domain name, or subdomain name (or any other criteria involving any or all three tables); Generally speaking if you want to find data in a db and use more than one query to get it - there's a more efficient way to do it.
Implementing the find call
There are a number of ways of creating such a query with Cake. The simplest, probably, is to use the join key and just specify the joins explicitly:
function fetchWithin($domains = null, $subdomains = null) {
$params = array(
'joins' => array(
array('table' => 'subdomains',
'alias' => 'Subdomain',
'type' => 'LEFT',
'conditions' => array(
'Subdomain.id = Item.subdomain_id',
)
),
array('table' => 'domains',
'alias' => 'Domain',
'type' => 'LEFT',
'conditions' => array(
'Domain.id = Subdomain.domain_id',
)
)
)
);
if ($domains) { // single value or an array
$params['conditions']['Domain.name'] = $domains;
}
if ($subdomains) { // single value or an array
$params['conditions']['Subdomain.name'] = $subdomains;
}
return $this->find('all', $params);
}

CakePHP sql-query

I have the following tables:
- restaurants (restaurant.id, restaurant.name)
- menus (menu.id, menu.name, menu.active, menu.restaurant_id)
I want to have a list with all restaurants with the active menus (menu.active = true):
- restaurant2
- menu1
- menu4
- restaurant5
-menu3
- restaurant19
- menu34
- menu33
My first idea was something like this:
$options['contain'] = array(
'Menu' => array(
'conditions' => $menuParams //array('Menu.active' => '1') //$menuParams
)
);
This doen't work becaus all restaurants will be listed. I want to have only restaurants with active menus.
Next idea: using join
$options['joins'] = array(
array('table' => 'menus',
'alias' => 'Menu',
'type' => 'RIGHT',
'conditions' => array(
'Menu.restaurant_id = Restaurant.id',
)
)
);
Not good, because, I don't have the ordered list I want. I need the menus grouped by the restaurant. Look above.
Is it the right way to make a join with restaurants and menus(active = true) and then using the contain to get the ordered list? I think that could work but I think also there is an easier way, right?
Any help is welcome! Thank you.
If you are using the ORM machinery from CakePHP, you should have a Restaurant model and a Menu model to describe each table. In the Restaurant model, you should have a $hasMany = "Menu" field, and in menu a $belongsTo = "Restaurant" field (assuming the model names are Menu and Restaurant).
From that point, doing queries using ORM is fairly straightforward:
$this->Restaurant->recursive = 1; // grab the menus
$conditions = array('Menu.active' => '1'); // restrict to active menus only
$this->Restaurant->find('all', array('conditions' => $conditions));
The above in the ad-hoc method of the Restaurant controller should retrieve the rows as an array of Restaurant objects, each bundled with an array of active Menu.
Now I found the easy and clean solution for my concern! Yeah!
First I had to unbind the bindings and then I had to make a new binding with the condition. It works like a charm. Here is the code:
$this->unbindModel(array('hasMany' => array('Menu')));
$this->bindModel(array('hasMany'=>array(
'Menu'=>array(
'foreignKey' => 'restaurant_id',
'conditions' => array(
'Menu.active' => 1
)
)
)));
I thank you all for your answers!

Cakephp model associastion

I have thee following simple model:
Item belongsTo CatalogItem
CatalogItem hasMany Item, and belongsTo Section
Section hasMany CatalogItem
I'm trying to get counts of items, grouped by catalogitem, for a certain section-
the equivalent of:
SELECT catalogitem.id, count(*) FROM section LEFT JOIN catalogitem ON section.id=catalogitem.section_id LEFT JOIN item ON item.catalogitem_id=catalogitem.id WHERE section.id=5 GROUP BY catalogitem.id
So simple in sql, yet I can't get it to work with cake models. Can anyone point as to how to do it with cake models, using the model->find?
I can't get it to group by correctly or join correctly on 3 tables :(
Edit:
highly prefer to get the info in single query
Here's a longer way, "cakeish" way:
class Item extends AppModel
{
/* snip */
var $virtualFields = array('item_count' => 'count(Item.id)');
function getCountForSection($sectionId)
{
$ca = $this->Catalogitem->find
(
'all',
array
(
'fields' => array('Catalogitem.id'),
'conditions' => array('Catalogitem.section_id' => $sectionId),
'recursive' => -1
)
);
$ca = Set::extract('/Catalogitem/id', $ca);
$ret = $this->find
(
'all',
array
(
'fields' => array('Item.catalogitem_id', 'item_count'),
'conditions' => array('Item.catalogitem_id' => $ca),
'group' => array('Item.catalogitem_id'),
'recursive' => -1
)
);
return $ret;
}
}
Then simply use it in your controller:
$ret = $this->Item->getCountForSection(1);
debug($ret);
How does it work:
Define a virtual field (cake 1.3+ only AFAIK) which will count items
Fetch all the Catalogitems belonging to a Section you're interested in
Use Set::extract() to get the Catalogitems in a simple array
Use the array of Catalogitems to filter Items while counting and grouping them
NB: You don't seem to be using Cake's naming conventions in your database. This may hurt you.
Sorry, in my first answer I somehow missed your GROUP BY requirement, which was the whole point of the question, I now realize. I haven't used this yet, but I came across it recently, and it looks like it might accomplish what you are looking for: Linkable Behavior.
http://planetcakephp.org/aggregator/items/891-linkable-behavior-taking-it-easy-in-your-db
Like Containable, but works with only right and left joins, produces much more compact queries and supports GROUP BY.
http://github.com/rafaelbandeira3/linkable
#azv
Would this work for you:
$section_id = 5;
$fields = array('CatalogItem.id as CatalogItemId', 'count(*) AS SectionCount');
$conditions = array('Section.id' => $section_id);
$joins = array(
array('table' => 'catalogitem',
'alias' => 'CatalogItem',
'type' => 'LEFT',
'conditions' => array('Section.id' => 'CatalogItem.section_id')
),
array('table' => 'item',
'alias' => 'Item',
'type' => 'LEFT',
'conditions' => array('Item.catalogitem_id' => 'CatalogItem.id')
));
$data = $this->Section->find('all',
array('fields' => $fields,
'conditions' => $conditions,
'joins' => $joins,
'group' => 'CatalogItem.id',
'recursive' => -1)
);
// access your data values
foreach ($data['Section'] as $i => $datarow) {
$catalogitem_id = $datarow['CatalogItemId'];
$section_count = $datarow['SectionCount'];
}
This way you are explicitly setting your joins and doing it all in one query. See here for more info on joins in Cake:
http://book.cakephp.org/view/1047/Joining-tables
Hope this helps. All the best,
-s_r