0

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.

4

2 に答える 2

1

私はついにドキュメント(http://book.cakephp.org/view/1390/Automagic-Form-Elements)で答えを見つけました。

そして解決策は次のとおりです。addメソッドのグループコントローラー:

$this->set('users', $this->Group->User->find('list'));

そして、ビューで:

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

素晴らしくてシンプル。とにかくありがとう!

于 2011-10-12T19:59:21.060 に答える
0

Group コントローラーの add-group 関数で変数を設定する必要があります。
$users = $this->Group->User->find('all', array('fields' => array('DISTINCT User.user_id')));
$this->set('user_ids', $users);

次に、ビューで、次のような入力を作成します。
echo $this->Form->input('user_id', array('options' => $user_ids));

于 2011-10-12T19:45:21.517 に答える