如何解决获取产品的总投入成本-CakePHP 4
我是CakePHP 4.x的新手。 假设数据库中有3个表:
1. Products
- title
- description
2. Recipes
- title
- unit
- input_price
3. Costs
- product_id
- recipe_id
- quantity
我想计算单个产品所有配方的总投入成本。
- 我应该编写哪个文件的功能?是src / Model / Entity / Product.php吗?
- 如何编写最快使用多次的功能?
请帮助我。谢谢!
解决方法
您是正确的src / Model / Entity / Product.php是编写函数的最佳位置,您的Product实体应具有有关食谱的信息,但为此您必须在src / Model / Table中正确配置表模型/ProductsTable.php。
赞:
$this->belongsToMany('Recipes',[
'foreignKey' => 'product_id','targetForeignKey' => 'recipe_id','joinTable' => 'Costs',]);
更多信息:https://book.cakephp.org/4/en/orm/associations.html#belongstomany-associations
然后在控制器上,您可以使用类似以下的内容:
$query = $products->find('all')->contain(['Recipes']);
foreach($query as $product){
$product->yourEntityFunctionName()
}
或者您可以使用聚合函数:https://book.cakephp.org/4.next/en/orm/query-builder.html#aggregates-group-and-having
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。