cakephp:如何显示外键 table 字段

cakephp: how to display foreign key table field

基本上,

数据库table:

  1. 产品:id,名称

  2. 评论:产品编号,评论

型号: product.php

class Product extends AppModel {
  public $hasMany = array('Comment'=>array('foreignkey'=>'productId'));
}

comment.php

class Comment extends AppModel {
  public $belongsTo = array('Product');
}

在产品index.ctp中,如何显示一条产品评论?我需要在 ProductsController.php 和 index.ctp 中写什么?

如果您遵循 CakePHP 约定 (CakePHP Convention over Configuration),那么所有这些都将自动为您完成,它需要将外键命名为 product_id 而不是 productId(尽管您已经设置了关系中的外键 - 按照约定从头开始更容易。

您还应该在关系中指定 class 名称:

public $hasMany = array(
    'Comment' => array(
        'className' => 'Comment',
        'foreignKey' => 'product_id'
    )
);

在你的情况下,你应该在控制器中做的是:

$products = $this->Product->find('all');

这将获取您的所有产品以及对这些产品的任何相关评论(以及您在产品模型中声明的任何其他相关模型)

如果您想了解更多有关此设置的信息,可以查看 CakePHP - Retrieving your data