Young Johnny
Young Johnny

Reputation: 21

HasOne associations table is not saving

Hi I'm trying to save data across 2 tables (Entries and Conditions) at the same time. Entries has a column called foreign_key which is a relation to the Conditions primary id.

I was testing the saving portion and one of my tables (Conditions) saved but my other table (Entries) did not.

Entry.php

protected $_accessible = [
        'metadata' => true,
        'type' => true,
        'foreign_key' => true,
        'created' => true,
        'modified' => true,
        'condition' => true
    ];

Condition.php

protected $_accessible = [
        'user_id' => true,
        'data' => true,
        'created' => true,
        'modified' => true,
        'user' => true,
        'entry' => true
    ];

ConditionsTable.php (where I declared the association)

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('conditions');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);

        $this->hasOne('Entries', [
            'foreignKey' => 'foreign_key',
            'bindingKey' => 'id',
            'propertyName' => 'entries',
            'joinType' => 'INNER'
        ]);
    }

DataControlellr.php (where I'm testing the saving)


        $this->loadModel('Conditions');

        $data = [
            'user_id' => 'b26ee991-a27c-441b-a78b-dd2a1dbf5164',

            'data' => json_encode(['test'=>1,'test2' => 2]),
            'entry' =>[
                'meta' => json_encode(['test'=>1,'test2' => 2]),
                'type' => 'conditions'
            ]
        ];

        $entity = $this->Conditions->newEntity($data,['associated' => 'Entries']);
        //dd($entity);
        dd($this->Conditions->save($entity));
        exit;   
    }

So again entries table is not saving a row and conditions is, I believe I'm using the right association (has one) but maybe that not the right logic? Much help is appreciated.

Upvotes: 0

Views: 63

Answers (1)

Greg Schmidt
Greg Schmidt

Reputation: 5099

The key in your data and your association name need to match. You probably want to change your association to this:

$this->hasOne('Entries', [
    'foreignKey' => 'foreign_key',
    'bindingKey' => 'id',
    'joinType' => 'INNER'
]);

assuming that the class for the fhir_entries table is called EntriesTable, not FhirEntriesTable.

Alternately, leave the association named as it is but change the propertyName to entry (hasOne properties should be singular). Or, change it to fhir_entry and the key in the data array from entry to fhir_entry to match.

Upvotes: 1

Related Questions