Cake php 4 使用数组中的关联保存数据

Posted

技术标签:

【中文标题】Cake php 4 使用数组中的关联保存数据【英文标题】:Cake php 4 saving data with Associations from array 【发布时间】:2021-07-10 05:46:58 【问题描述】:

我正在尝试使用数组中的关联保存数据 我试图遵循一个例子 https://book.cakephp.org/4/en/orm/saving-data.html,转换 HasMany 数据

$data = [
    'title' => 'My Title',
    'body' => 'The text',
    'comments' => [
        ['id' => 1, 'comment' => 'Update the first comment'],
        ['id' => 2, 'comment' => 'Update the second comment'],
        ['comment' => 'Create a new comment'],
    ],
];

我找不到有效的示例。 我有 2 个表中定义的用户和地址 https://github.com/uvauser/test

当我尝试跟随任何控制器动作时:

      $this->loadModel('Users');
      $data = [
         'email' => 'test@test.nl',  
        'password' => 'Tdsaw3cds32',  
        'Addresses' => [  
            [
                'street' => 'My Street',  
                'house_number' => 23,  
                'postal_code' => '1234ab',  
                'city' => 'My City',  
                'country' => 'My Country'  
             ]
        ],
    ];  

    // Trial 1
    $user1 = $this->Users->newEntity($data, [  
       'associated' => ['Addresses' =>['validate'=>false]]
    ]);  
    $this->Users->save($user1);
   
     // Trial 2
    $user2 = $this->Users->newEmptyEntity();
    $entity = $this->Users->patchEntity($user2, $data, [
        'associated' => ['Addresses' =>['validate'=>false]]
    ]);
    $this->Users->save($user2);
    

它不保存。 谁能给我一个完整的工作示例

【问题讨论】:

"doesn't work" 不是正确的问题描述,请在描述问题时更加具体并说明究竟发生了什么,并且您希望确切地发生什么,例如用户数据可能会被保存,但地址不会。 【参考方案1】:

首先,将“地址”更改为小写的“地址”:

$data = [
         'email' => 'test@test.nl',  
        'password' => 'Tdsaw3cds32',  
        'addresses' => [ // <------------- 

然后:

https://github.com/uvauser/test/blob/main/Model/Entity/User.php

 /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        'email' => true,
        'password' => true,
        'created' => true,
        'modified' => true,
        'addresses' => true, // <---------- Add Addresses to $_accessible array
    ];

总是尝试使用调试功能来检测问题,例如:

debug($user1);

了解更多:

https://book.cakephp.org/4/en/orm/entities.html#mass-assignment

【讨论】:

以上是关于Cake php 4 使用数组中的关联保存数据的主要内容,如果未能解决你的问题,请参考以下文章

使用 Cake 2.4.5 保存用户和详细信息行

CakePHP- 保存相关模型数据

如何从 jqgrid 发送 CSRF 令牌

如何在 Cake PHP 3.5 中设置模型之间的关联?

Cake 2 复杂 habtm 关系的数据模型 - 保存和加载

如何在 Cake 3.0 中保存 belongsToMany 数据?