Reputation: 1890
I Seem to really be struggling to find any information actually covering the use of Virtual Fields in CakePHP. Yes I know there is official documentation on the CakePHP site, however it does not cover the use of separate tables.
Eg
Table: Products
ID | PRODUCT | PRICE | QUANTITY
1 | Butter | 2.50 | 250
2 | Flour | 6.00 | 16000
3 | Egg | 0.99 | 6
Table: Products_Recipes
Product_ID | Recipe_ID | Quantity | COST ("VIRTUAL FIELD")
1 | 1 | 200 |= SUM (Products.Price/Products.Quantity) * Products_Recipes.Quantity
2 | 1 | 400
3 | 1 | 3
Table: Recipes
ID | RECIPE | COST ("Virtual Field")
1 | Pastry | Sum of Costs where Recipe_id is 1
Bit of a newbie to Mysql however I think this is the way I should be doing it. How do I then use Virtual Fields to access this information? I can get it to work in one model but not to access other models?
Doug.
Upvotes: 0
Views: 858
Reputation: 5271
I assume your tables are such:
(The missing fields are those you are trying to create.)
I find it easier to create in MySQL, then when it works decide if MySQL or CakePHP is the right place for production implementation. (And, you require a bit more complexity than the CakePHP examples.)
To create a working solution in MySQL:
Create a select view for the products_recipes
CREATE VIEW vw_recipe_products AS
SELECT products_recipes.product_id, products_recipes.recipe_id, products_recipes.quantity,
,(Products.Price/Products.Quantity) * Products_Recipes.Quantity as COST
FROM products_recipes
JOIN products
ON products_recipes.product_id = products.product_id
(I don't think you should have the SUM operator, since you there is no need for a GROUP BY clause)
Then the recipes
CREATE VIEW vw_recipes_with_cost
SELECT recipes.id, recipes.recipe, SUM(vw_recipes_products.cost) as cost
FROM recipes
JOIN vw_recipes_products
ON recipes.id = vw_recipes_products.recipe_id
GROUP BY recipes.id, recipes.recipe
Ultimately, I think you should be implementing the solution in MySQL due to the GROUP BY clause and use of the intermediary view. (Obviously, there are other solutions, but take advantage of MySQL. I find the CakePHP implementation of virtual fields to be used for simple solutions (e.g., concatenating two field)) {Once you create the views, you will need to create new models or change the useTable variable of existing tables to use the views instead.}
Upvotes: 1