与 CakePHP 的简单关联
我最近开始研究 CakePHP——到目前为止我很喜欢它。然而,我需要问一个相当简单的问题:
这是关于模型关联的。我有 2 个模型用户和组。一个用户可以有多个组,一个组只能有一个用户。所以我做了这样的:
<?php
class Group extends AppModel {
var $name = 'Group';
var $belongsTo = 'User';
}
?>
<?php
class User extends AppModel {
var $name = 'User';
var $hasMany = 'Group';
}
?>
然后在添加组页面上我希望可以从下拉列表中选择用户。我的组添加视图如下:
<h1>Add Group</h1>
<?php
echo $this->Form->create('Group');
echo $this->Form->input('user_id');
echo $this->Form->input('name');
echo $this->Form->input('pincode');
echo $this->Form->input('private');
echo $this->Form->end('Create group');
?>
user_id 自动转换为下拉列表 - 但没有任何选项。我需要做什么?我假设我需要放在某个地方,它应该从用户表中获取“名称”。
I recently started looking into CakePHP - which I'm so far loving. However, I need to ask a fairly simply question:
It's about model association. I got 2 models User and Group. A User can have multiple Groups and a Group can only have one User. So I've made it like this:
<?php
class Group extends AppModel {
var $name = 'Group';
var $belongsTo = 'User';
}
?>
<?php
class User extends AppModel {
var $name = 'User';
var $hasMany = 'Group';
}
?>
And then on the add-group page I want it to be possible to select the user from a dropdown. My Group add view is as follows:
<h1>Add Group</h1>
<?php
echo $this->Form->create('Group');
echo $this->Form->input('user_id');
echo $this->Form->input('name');
echo $this->Form->input('pincode');
echo $this->Form->input('private');
echo $this->Form->end('Create group');
?>
The user_id automatically transforms to a dropdown - however without any options. What do I need to do? I assume I need to put somewhere that it should get the "name" from the User table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我终于在文档中找到了答案(http://book.cakephp.org/view/1390/Automagic-Form-Elements)。
解决方案是:
添加方法中的组控制器:
和视图中:
漂亮又简单。无论如何,谢谢!
I finally found the answer in the documentation (http://book.cakephp.org/view/1390/Automagic-Form-Elements).
And the solution is:
Group controller in the add method:
And in the view:
Nice and simple. Thanks anyway!
您应该在组控制器的添加组函数中设置一个变量:
$users = $this->Group->User->find('all', array('fields' => array('DISTINCT User.user_id')));
< br>$this->set('user_ids', $users);
然后在视图中创建如下输入:
echo $this->Form->input('user_id', array('options' => $user_ids));
You should set a variable in the Group controller's add-group function:
$users = $this->Group->User->find('all', array('fields' => array('DISTINCT User.user_id')));
$this->set('user_ids', $users);
Then in the view, create the input like this:
echo $this->Form->input('user_id', array('options' => $user_ids));