【问题标题】:$belongsTo relationship not working cakephp 2.7.5$belongsTo 关系不工作 cakephp 2.7.5
【发布时间】:2016-01-14 02:18:59
【问题描述】:

我正在尝试链接两个模型以在我的 cakephp 2.7.5 应用程序中工作。

问题是当我尝试添加新的“用户”时,表单没有显示带有我创建的“部门”选项的“选择”。

代码是:

app\Model\User.php

<?php

class User extends AppModel {
    public $name = "User";
    public $belongsTo = array('Departamento' => array('className' => 'Departamento', 'foreignKey' => 'departamento_id'));
...

app\Model\Departamento.php

<?php

class Departamento extends AppModel {

    public $displayField = 'nombre';
    public $name = "Departamento";
    public $hasMany = array('User' => array('className' => 'User', 'foreignKey' => 'departamento_id'));

}

这是 MySQL 脚本:

create table users(
    id int primary key auto_increment,
    nombre varchar(200),
    username varchar(20) not null,
    password varchar(100) not null,
    rol varchar(50) not null,
    departamento_id int
);

create table departamentos(
     id int primary key auto_increment,
    nombre varchar(200) not null
);

我的 app\View\Users\add.ctp 代码:

echo $this->Form->create('User');
echo $this->Form->input('nombre', array('label' => 'Nombre Completo:'));
echo $this->Form->input('username', array('label' => 'Nombre de usuario:'));
echo $this->Form->input('password', array('type' => 'password', 'label' => 'Contraseña:'));
echo $this->Form->input('rol', array('label' => 'Rol del usuario:', 'type' => 'select', 'options' => array('ADMINISTRADOR' => 'Administrador', 'USUARIO' => 'Usuario')));
echo $this->Form->input('departamento_id', array('label' => 'Departamento:'));
echo $this->Form->end('Guardar');

我已将变形规则添加到我的西班牙语命名表中:

Inflector::rules('plural', array('irregular' => array('departamento' => 'departamentos')));

这是我的“添加用户”表单的屏幕截图,“Departamento”字段显示为空,但我的“Departamentos”表中有数据:

Add Form with empty field

谢谢

【问题讨论】:

  • 你能从UsersController粘贴你的添加动作吗?

标签: php mysql cakephp


【解决方案1】:

只需添加以下内容:

$this->set('departamentos',$this->User->Departamento->find('list',array('order'=>'nombre')));

在您的 UsersController::add() 函数中。 CakePHP 应该从视图中的 $departamentos 变量自动创建 SELECT 选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多