HasOne关联表未保存

时间:2019-04-12 14:15:37

标签: cakephp cakephp-3.0

嗨,我正在尝试同时保存2个表(条目和条件)中的数据。条目具有称为foreign_key的列,该列与“条件”主ID相关。

我正在测试保存部分,并且保存了我的一个表(条件),但没有保存其他表(条目)。

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(我在其中声明了关联)

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(我正在测试保存的位置)


        $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;   
    }

所以再次,entries表没有保存行,条件是,我相信我使用的是正确的关联(有一个),但是也许这不是正确的逻辑?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

数据中的密钥和关联名称需要匹配。您可能想将您的关联更改为此:

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

假设fhir_entries表的类称为EntriesTable,而不是FhirEntriesTable

或者,保留关联名称不变,但将propertyName更改为entryhasOne属性应为单数)。或者,将其更改为fhir_entry,并将数据数组中的键从entry更改为fhir_entry以匹配。

相关问题