Foreign key constraint when using Drop down


#1

I need some help with using a drop down box with a foreign key relationship. I have got the drop down filling in the correct values but the only problem is when i add a user there is a foreign key constraint. But I can make users if i just use the normal input box and type an id that exists in the other table.
for example when i enter the id with this in my add.ctp it works
echo $this->Form->input(‘location’);
but when i use this it doesn’t
echo $this->Form->input(‘location_id’, array(‘type’ => ‘select’, ‘options’ => $CompanyLocations));

This is my add function in my 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']);

This is in my UsersTable
$this->belongsTo(‘CompanyLocations’);

and my 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'
    ]);
}

and my mysql code

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;


#2

I solved the problem by renaming my tables