CakePHP: SQL Query to Cake->find()
Firstly, here's my database relation diagram.
I'm trying to make a diagram with the number of a certain element ordered for each day
date | count
2011-04-22 | 10348
2011-04-23 | 2751
Since I'm more familiar with SQL, I've that that first, and this is what finally came out (and works)
SELECT dn.delivery_date, SUM(dnp.count*ep.count) as count
FROM
`delivery_notes` AS dn JOIN `delivery_notes_products` AS dnp
ON dn.id = dnp.delivery_note_id
JOIN `products` AS p
ON dnp.product_id = p.id
JOIN `elements_products` AS ep
ON p.id = ep.product_id
JOIN `elements` AS e
ON ep.element_id = e.id
WHERE e.id = 4
AND dn.delivery_date BETWEEN '2011-04-22' AND '2011-05-22'
GROUP BY dn.delivery_date
Now to improve my get some Cake-find skills, I'm trying to u开发者_开发技巧nderstand how to turn this into a find('list') or find('all') query, yet I really have NO idea how I should tackle this one...
Any help would be greatly appreciated.
$this->DeliveryNote->bindModel(array(
'hasOne'=>array(
'DeliveryNotesProduct'=>array(
'conditions'=>array('DeliveryNotesProduct.DeliveryNoteId = DeliveryNote.id')
),
'Product'=>array(
'conditions'=>array('DeliveryNotesProduct.ProductId = Product.id')
),
'ElementsProduct'=>array(
'conditions'=>array('ElementsProduct.ProductId = Product.id')
),
'Element'=>array(
'conditions'=>array('ElementsProduct.ElementId = Element.id')
)
)
));
$data = $this->DeliveryNote->find('all',array(
'conditions'=>array(
'Element.id'=>4,
'DeliveryNote.DeliveryDate BETWEEN ? AND ?'=>array('2011-04-22','2011-05-22')),
'fields'=>array('DeliveryNote.DeliveryDate','SUM(DeliveryNotesProduct.Count * ElementsProduct.Count) AS count'),
'group'=>array('DeliveryNote.DeliveryDate')
));
Cakephp bindModel
is used for joining tables and hasOne
is one of the association type
http://book.cakephp.org/view/1040/Relationship-Types
精彩评论