CakePHP:ID 饥饿让我发疯

问题描述 投票:0回答:2

出于数据完整性原因,我尝试在我的用户/注册中填充一个超简单的下拉“国家/地区”

由于 Country 和 User 没有关系(请不要对此发表评论,这是有原因的。如果 Country 是 FK,Cake 的行为方式相同),我按如下方式检索 users_controller 中的国家/地区,这两种方法都不会阻止仅保存country_id的蛋糕:

$this->set('countries', ClassRegistry::init('Country')->find('list'));

$this->set('countries', ClassRegistry::init('Country')->find('list', array('fields' => array('Country.country'))));

显示字段设置为:国家/地区。

在我的register.ctp中,输入设置为:

echo $this->Form->input('country');

国家/地区在下拉列表中显示得很好。但无论我尝试什么,只有国家/地区 ID 会保存到用户表中。我删除了表中的ID并将国家作为我的PK。 Cake 开始谈论“缺失的栏目”Country.id。

如何解决这个简单的问题,还是我必须切换回简单的无框架 PHP,这需要我 30 秒才能解决。

谢谢!

php cakephp cakephp-1.3
2个回答
1
投票

如果我理解正确的话,该值和国家/地区的显示名称应该相同。 Cake 的

find('list')
方法默认为
id => name
列表,您可以使用
fields
参数进行自定义(您需要提供两个字段)。我不知道如果您两次提供相同的字段这是否有效,您可能想尝试一下。

如果 automagic

find('list')
方法的约定不适合您的用例,您可以通过多种方式自行创建列表。最简单的是,使用
find('list')
,然后只需将值复制到键即可:

$countries = $this->Country->find('list');
$countries = array_combine($countries, $countries);

如果您的

id
表中根本没有
country
字段,只需使用普通的
find('all')
并构建自己的数组:

$countries = $this->Country->find('all');
$countries = array_map(function ($country) { return $country['Country']['name']; }, $countries);
$countries = array_combine($countries, $countries);

最后但并非最不重要的一点是,您可以放弃 Cake Form 帮助程序,它需要一个

value => name
数组作为其选项,并以原始 PHP 输出您自己的国家/地区列表。

Cake 的约定是为了确保典型模式的安全时间。如果您的模式不典型,CakePHP 中仍然有 PHP。


1
投票

只需使用这个:

$this->set('countries', ClassRegistry::init('Country')->find('list', array('fields' => array('Country.country','Country.country'))));

© www.soinside.com 2019 - 2024. All rights reserved.