0

I have People belongsToMany Phones. Can I save a person with its phone in one save() like this?

in PeopleTable:

$this->belongsToMany('Phones', [
    'foreignKey' => 'person_id',
    'targetForeignKey' => 'phone_id',
    'joinTable' => 'people_phones'
]);

in add.ctp:

$this->Form->create($person);
$this->Form->input('person_name');
$this->Form->input('phones.0.phone_number');

in PeopleController:

$person = $this->People->patchEntity($person, $this->request->data, ['associated' => ['Phones']]);
$this->People->save($person, ['associated' => ['Phones']])

But only the person gets saved, without the phone. No error message. Is it even possible to save it like this?

I have CakePHP 3.0.2 (updated today)

Mabye I should add that I'm a beginner, never coded in OOP before, and I tortured google for two days now without any relevant answer. Simply "yes, it should work this way, you must have some error there" or "no, you must save Phone first to get its ID" would be sufficient :) Thanks

Cœur
  • 37,241
  • 25
  • 195
  • 267
leeroy
  • 1
  • 1
  • Looks good to me... what does your `Person` entity class look like, specifically its `$_accessible` property? Also could you add a debug dump of `$person` (`debug($person);`) after patching and show the results? – ndm Apr 24 '15 at 13:03
  • @ndm You are right! Thank you so much! I didn't have "phones" in $_accessible. I will write the result form of Person entity in the answer – leeroy Apr 24 '15 at 19:49

1 Answers1

0

Thanks to @ndm the problem was found in Person entity class in $_accessible property. It should look like this:

protected $_accessible = [
    'person_name' => true,
    'phones' => true,
];

Now it works perfectly! Thank you very much

leeroy
  • 1
  • 1