Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to execute a query to get my data
how can I write this query with cakephp
select materiel_id , SUM(quantite) from paiements
GROUP BY
materiel_id
ORDER BY sum(quantite)
Thinks,
PS : I use cakephp 2.3.6
Well assuming you have the model relationship Paiement belongsTo Materiel and you are in the PaiementsController
$this->Paiement->find('all',
array(
'group' => array('Paiement.materiel_id'),
'fields' => array('Paiement.materiel_id),
'contain' => array(
'Materiel' => array(
'fields' => array(
'SUM(Paiement.quantite) AS sum'
),
'order' => array(
'sum' => 'desc'
),
), // Materiel
) // contain
) // end array
); // end find
you ca us this code
$mat=$this->Materiel->Paiement->query("
select *,materiel_id , SUM(paiements.quantite) as t from paiements ,materiels
where paiements.materiel_id=materiels.id
GROUP BY
materiel_id
ORDER BY sum(paiements.quantite) desc
");
Ajust this code for your model
Related
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!
I have a Device Table containing different ids from different tables e.g. Location, Operators etc.
now I want only some of them shown in my view. so there is an array device_ids with the corresponding ids I want to Show.
I tried
$this->paginate['contain'] = ['Locations', 'Operators'];
and this shows me all devices with all corresponding Data.
I tried
$this->paginate['conditions'] = ['id IN' => $device_ids];
and this Shows me only the devices I want to view, but without corresponding Data.
as soon as I Combine those two in
$this->paginate[] = [
'conditions' => ['id IN' => $device_ids],
'contain' => ['Locations', 'Operators']
];
I receive a
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in IN/ALL/ANY subquery is ambiguous.
Has anyone has an Explanation for this behaviour?
What could I change to make this work.
Thanks a lot
L.
sorry,
as soon as I posted the question the answer was there...
I needed to specify the id more,
so with
$this->paginate[] = [
'conditions' => ['Devices.id IN' => $device_ids],
'contain' => ['Locations', 'Operators']];
it works fine.
Thanks for your time
You should add model name with field like ModelName.id
$this->paginate['conditions'] = ['ModelName.id IN' => $device_ids];
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).
Guys help me to do this. I'm new to YII. I want to display each item branches stock like this.
actual database
What is the best way to do this?
What you are looking for is a cross tab or pivot table. Here is a link: http://www.artfulsoftware.com/infotree/qrytip.php?id=523
I have been looking for the same thing and have a solution using CSqlDataProvider. It is important to note when using CSqlDataProvider it returns an array unlike CActiveDataProvider which returns an object.
Here is the model code
public function displayStock($id)
{
$sql='SELECT product_id, COUNT(*) as productCount FROM stock WHERE assigned_to = 2 GROUP BY product_id';
$dataProvider=new CSqlDataProvider($sql, array(
'pagination'=>array(
'pageSize'=>10,
),
));
return $dataProvider;
}
Here is the code for the veiw
$stockDataProvider = Stock::model()->displayStock(Yii::app()->user->id);
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'stock-grid',
'ajaxUpdate' => true,
'template'=>'{items}{summary}{pager}',
'dataProvider'=>$stockDataProvider,
'columns'=>array(
'product_id',
array(
'name'=>'test',
'value'=>'$data["productCount"]'
),
array(
'class' => 'CButtonColumn',
'template' => '{view} {update}',
),
),
));
When defining the SQL statement in the model, you can see we have set the COUNT(*) to be called productCount. Then in the view we reference that name in the columns array like so
array(
'name'=>'test',
'value'=>'$data["productCount"]'
),
So simply replace productCount with the name you have used.
I'm sure the above code could do with some tweaking ie using Binded params in the query etc, but this has worked for me.
Any comments or improvements are very welcome. I'm only about 8 months into php and 3 months into yii.
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);
}