2015-08-19 30 views
2

我是cakephp的新手。 http://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associationshttp://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations的文檔對於像我這樣的初學者來說似乎過於簡單或非常先進。如何在Cake 3.0中保存belongsToMany數據?

從我所能理解的,我做了以下。

//Table Baskets belongsToMany Apples 
//At BasketsTable.php in initialize() 
$this->belongsToMany('Apples',[ 
      'joinTable' => 'apples_baskets' 
     ]); 

一個在MySQL連接表apples_baskets

+---+---------+----------+ 
|id |apple_id |basket_id | 
-------------------------- 
| |   |   | 
-------------------------- 

我已經出現在控制器作爲POST請求的數據:

Array 
(
    [id] => 1 
    [xyz] => blahblah 
    [apples] => Array 
     (
      [_ids] => Array 
       (
        [0] => 1 
       ) 

     ) 

    [amount] => 15000 
) 

現在,當我執行save,只有籃子表得到更新,連接表保持不變,並且不會引發錯誤。

我知道我肯定錯過了一些東西,但無法弄清楚。請幫忙 !!!

回答

2

請檢查您Baskets實體類使其​​財產_accessible

<?php 
namespace app\Model\Entity; 

use Cake\ORM\Entity; 

class Basket extends Entity { 
    public $_accessible = [ 
     'apples', // <-- make sure this is present 
    ]; 
} 

具有這些新的實體類試圖加載它們與數據(使用Table::newEntity()Table::patchEntity())工作時很常見的問題,但由於質量分配保護,某些數據實際上並未保存到實體中。

Ref:http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment