Reputation: 39
I am new to cakephp. The documentation at http://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations and http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations seem either too brief or very advanced for a beginner like me.
From what I could understand, I have done the following.
//Table Baskets belongsToMany Apples
//At BasketsTable.php in initialize()
$this->belongsToMany('Apples',[
'joinTable' => 'apples_baskets'
]);
A join table apples_baskets
in MySQL:
+---+---------+----------+
|id |apple_id |basket_id |
--------------------------
| | | |
--------------------------
I have made the post request data to appear at the controller as:
Array
(
[id] => 1
[xyz] => blahblah
[apples] => Array
(
[_ids] => Array
(
[0] => 1
)
)
[amount] => 15000
)
Now when I perform save
, only the Baskets table gets updated, the join table remains untouched, and no error is thrown.
I know I am surely missing something but cant't figure out. Please help !!!
Upvotes: 2
Views: 4233
Reputation: 3970
Try checking that your Baskets
Entity class makes its apples
property _accessible
:
<?php
namespace app\Model\Entity;
use Cake\ORM\Entity;
class Basket extends Entity {
public $_accessible = [
'apples', // <-- make sure this is present
];
}
A pretty common gotcha when working with these new Entity classes trying to load them up with data (using Table::newEntity()
or Table::patchEntity()
), but some of that data not actually getting saved into the Entity due to the mass-assignment protection.
Ref: http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment
Upvotes: 5
Reputation: 93
Look here: http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
Try setting $basket->dirty('apples', true);
. This should tell cake there's unsaved associations here that it needs to take care of.
Upvotes: 2