Saving Has and BelongsTo Many Associations with Array Push


#1

In the CakePHP book they show you one technique for saving associated data:

https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations

$article->comments[] = $comment;
$article->dirty(‘comments’, true);

I found myself having to debug this in the framework code and (if I remember correctly), the association property wasn’t set in the Entity->_properties array.

class EvaluationAnswerSet extends Entity
{
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];


...


class EvaluationAnswerSetsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);
        ...
        $this->hasMany('EvaluationAnswers', [
            'className' => 'HCP/Core.EvaluationAnswers',
            'foreignKey' => 'answer_set_id'
        ]);
    }

    ...

//Simplification of code that adds an associated answer
$answer = new \Cake\ORM\Entity\EvaluationAnswer();
$evaluation_answer->evaluation_answers[] = $answer;
$evaluation_answer->dirty('evaluation_answers', true);
$EvaluationAnswerSetsTable->save($evaluation_answer);

With the above example, the associated entity was not being persisted to the database.

I’m not 100% certain that it was the _properties array that wasn’t getting populated that was the reason the save was failing or if it was some other property, but I feel like this should be handled by the framework when defining an association.

If anyone could provide further insight into this it would be much appreciated.

Edit:
I’m aware that I can use the following technique to get this to work:
$answer = new \Cake\ORM\Entity\EvaluationAnswer(); $evaluation_answers = $evaluation_answer->evaluation_answers; $evaluation_answers[] = $answer; $evaluation_answer->evaluation_answers = $evaluation_answers; $EvaluationAnswerSetsTable->save($evaluation_answer);
However, the I feel like the book’s documentation should work and I’m concerned that there may be an issue with the way the associations or entities were defined.


#2

Can you show a debug(evaluation_answer) after what you are doing?

The key to make it save is to make sure that evaluation_answers is marked as dirty.