在 CakePHP 3 中保存 belongstomany 关系

Saving belongstomany relations in CakePHP 3

我被这个问题困扰了一段时间,我似乎找不到我的代码有什么问题。我有以下 3 个表,其中零售商有很多客户,客户可以有很多零售商,这是 CakePHP 3 中的 belongstomany 关系。2 之间的关系存储在 clients_retailers table 中。

class ClientsTable extends Table
{
        ...
        $this->belongsToMany('Retailers', [
            'joinTable' => 'clients_retailers'
        ]);
}

class RetailersTable extends Table
{

    public function initialize(array $config)
    {
        ...

        $this->belongsToMany('Clients', [
            'joinTable' => 'clients_retailers'
        ]);
    }
}

class ClientsRetailersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('clients_retailers');
        $this->displayField('client_id');
        $this->primaryKey(['client_id', 'retailer_id']);

        $this->belongsTo('Clients', [
            'foreignKey' => 'client_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Retailers', [
            'foreignKey' => 'retailer_id',
            'joinType' => 'INNER'
            ]);
        }
}

然后在客户端控制器的添加函数中,我试图保存新客户端和零售商之间的这种关系。

 public function add()
        {
            $client = $this->Clients->newEntity();
            if ($this->request->is('post')) {
                $retailer_id = $this->Auth->user('retailer_id');
                $retailer = [
                    'retailers' => [
                        [
                            'id' => $retailer_id
                        ]
                    ]
                ];
                $client = $this->Clients->patchEntity($client, $this->request->data);
                $client = $this->Clients->patchEntity($client, $retailer, ['associated' => [
                        'Retailers'
                    ]]);


                if ($this->Clients->save($client)) {
                    $this->Flash->success(__('The client has been saved.'));
                   return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The client could not be saved. Please, try again.'));
                }
            }
        }

新客户端永远不会添加到数据库中。我在网上看到它可能是一个验证问题,所以我尝试使用 ['validate' => false],但它似乎没有改变任何东西。保存功能只是失败而没有错误。

最糟糕的是,当从 api 控制器中的另一个函数调用时,这种关系过去常常被正确保存。我当然尝试复制它,但它似乎在这个控制器中不起作用。有谁知道问题可能出在哪里。非常感谢!

更新: 这是我要保存的客户端实体值

object(App\Model\Entity\Client) {

    'firstname' => 'test',
    'lastname' => 'test',
    'email' => 'test@email.com',
    'password' => 'hash',
    'retailers' => [
        (int) 0 => object(App\Model\Entity\Retailer) {

            'id' => '1',
            'name' => 'TestRetailer',
            'created' => object(Cake\I18n\Time) {

                'time' => '2017-12-20T20:13:58+00:00',
                'timezone' => 'UTC',
                'fixedNowTime' => false

            },
            'modified' => object(Cake\I18n\Time) {

                'time' => '2017-12-20T20:13:58+00:00',
                'timezone' => 'UTC',
                'fixedNowTime' => false

            },
            '[new]' => false,
            '[accessible]' => [
                '*' => true,
                'id' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'Retailers'

        }
    ],
    '[new]' => true,
    '[accessible]' => [
        '*' => true,
        'id' => true
    ],
    '[dirty]' => [
        'firstname' => true,
        'lastname' => true,
        'email' => true,
        'password' => true,
        'retailers' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Clients'

}

您需要更改代码才能正常工作,

public function add()
        {
            $client = $this->Clients->newEntity();
            if ($this->request->is('post')) {
                $retailer_id = 'XXXXXX'
                $retailer = [
                    'retailers' => [
                        [
                            'id' => $retailer_id
                        ]
                    ]
                ];
                $client = $this->Clients->patchEntity($client, $this->request->data, ['validate' => false]);   //Validation false
                $client = $this->Clients->patchEntity($client, $retailer, ['associated' => [
                        'Retailers' => ['validate' => false]   //You need to disable validation here too
                    ]]);


                if ($this->Clients->save($client)) {
                    $this->Flash->success(__('The client has been saved.'));
                   return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The client could not be saved. Please, try again.'));
                }
            }
        }

我终于明白问题出在哪里了。我在客户端 table 的查找功能上有一个 beforeFind 行为,但我没有意识到这会导致保存失败