我是CakePHP 4.x的新手。假设数据库中有3个表:
1. Products
- title
- description
2. Recipes
- title
- unit
- input_price
3. Costs
- product_id
- recipe_id
- quantity我想计算一个单一产品的所有食谱的总投入成本。
请帮帮我。谢谢!
发布于 2020-09-23 19:07:44
您是对的,src/Model/ entity /Product.php是编写函数的最佳位置,您的Product.php应该拥有关于Recipes的信息,但为此您必须在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()
}或者您可以使用agregations函数:https://book.cakephp.org/4.next/en/orm/query-builder.html#aggregates-group-and-having
https://stackoverflow.com/questions/64032050
复制相似问题