cakephp Cake php 4从数组中保存关联数据

qij5mzcb  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(141)

我尝试保存数组中具有关联的数据我尝试遵循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);

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

vsnjm48y

vsnjm48y1#

首先,将“Addresses”更改为小写“addresses”:

$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

相关问题