使用带有外键关系的下拉框我需要一些帮助。我有下拉填充正确的值,但唯一的问题是当我添加用户有一个外键约束。但是如果我只使用普通输入框并输入另一个表中存在的id,我可以创建用户。 例如,当我在add.ctp中输入id时,它可以正常工作
echo $this->Form->input('location');
但是当我使用它时它不会
echo $this->Form->input('location_id', array('type' => 'select', 'options' => $CompanyLocations));
这是我在UsersController中的添加功能
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$CompanyLocations= $this->Users->CompanyLocations->find('list');
$this->set(compact('CompanyLocations'));
$this->set(compact('user'));
$this->set('_serialize', ['user']);
这是在我的UsersTable
中 $this->belongsTo('CompanyLocations');
和我的CompanyLocationsTable
public function initialize(array $config)
{
parent::initialize($config);
$this->table('company_locations');
$this->displayField('location_name');
$this->primaryKey('location_id');
$this->belongsTo('Locations', [
'foreignKey' => 'location_id',
'joinType' => 'INNER'
]);
}
和我的mysql代码
CREATE TABLE IF NOT EXISTS southpac_team.company_locations (
location_id INT NOT NULL AUTO_INCREMENT,
location_name VARCHAR(45) NULL,
PRIMARY KEY (location_id))
ENGINE = InnoDB;
DROP TABLE IF EXISTS southpac_team.users ;
CREATE TABLE IF NOT EXISTS southpac_team.users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
department INT NULL,
mobile VARCHAR(255) NULL,
email VARCHAR(255) NULL,
extension INT NULL,
lame_number INT NULL,
spa_auth_number VARCHAR(15) NULL,
creation_date DATE NULL,
picture VARCHAR(255) NULL,
employed TINYINT(1) NOT NULL,
location INT NOT NULL,
PRIMARY KEY (id),
INDEX get location_idx (location ASC),
CONSTRAINT get location
FOREIGN KEY (location)
REFERENCES southpac_team.company_locations(location_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
答案 0 :(得分:0)
您没有遵循命名约定,默认情况下,belongsTo
关联的外键名称是关联别名的单数下划线变体,后缀为_id
,因此在{{1}的情况下这将是CompanyLocations
,而不仅仅是company_location_id
。
location
持有列表的变量也应该使用驼峰外壳,那么你甚至不需要通过options参数指定它:
echo $this->Form->input('company_location_id');
如果您正在使用无法修改的旧数据库,则需要相应地配置CakePHP,即通过$companyLocations= $this->Users->CompanyLocations->find('list');
$this->set(compact('companyLocations'));
的options参数指定自定义外键。
Table::belongsTo()
$this->belongsTo('CompanyLocations', [
'foreignKey' => 'location'
]);
中的belongsTo
关联看起来也很可疑,除非你真的有一个CompanyLocationsTable
与LocationsTable
相关联:
CompanyLocationsTable
我猜你已经通过bake创建了模型,它将company_locations.location_id > locations.primary_key
视为外键,因为它匹配location_id
关联的默认外键命名方案。