1

我是 MVC 编程的新手(甚至是基于对象的)。所以来自 PhP 4.* 我进入了 OOP、MVC 和 Cake..

我正在建立一个网站,来自不同国家的机构可以用来存储他们的数据(以及更多)。我现在正在建立每个机构的基本注册,并希望包括一个国家的下拉列表。

我看到了两种方法来解决这个问题;使用 Country 模型检索下拉列表的国家/地区表信息:( $this->set('countries', ClassRegistry::init('Country')->getAllCountries()); 后跟 \Model\Country.php 中的函数)

或使用 InstitutesController:
$this->set('countries', $this->Institute->Country->find('list', $params = array('fields' => array('id', 'country'))));

哪条是推荐的路线,因为两者似乎都有效?

4

1 回答 1

0

使用第二个:

$this->set('countries', $this->Institute->Country->find('list', $params = array('fields' => array('id', 'country'))));

两者都有效,但是,您已经获得了国家模型的实例(可通过 $this->Institute->Country 访问)。那么,为什么要创建它的另一个实例呢?只是没有必要。

实际上不需要为调用 find 方法指定字段。'id' 将被自动选择为第一个字段,如果您将 Country 模型的显示字段设置为 'country',那么这将是 find('list') 调用中的默认用途。像这样做:

// just after class Country extends AppModel {
public $displayField = 'country';

然后,您只需要使用以下代码:

$this->set('countries', $this->Institute->Country->find('list'));
于 2013-10-13T22:51:17.067 回答