Cakephp3在保存时设置关联ID

时间:2015-04-15 16:08:55

标签: php cakephp cakephp-3.0

我目前有一个Products表,属于Artists表。我想在Products控制器的add操作上手动设置所创建产品的artist_id外键。它给了我一个验证错误:

添加操作:

public function add($artist_id)
{
    $artist = $this->Products->Artists->get($artist_id, [
        'contain' => []
    ]);
    $product = $this->Products->newEntity();
    if ($this->request->is('post')) {
        $product->artist = $artist;
        $product = $this->Products->patchEntity($product, $this->request->data, [
            'fieldList' => [
                'photo', 'name', 'price', 'reference'
            ]
        ]);
        if ($this->Products->save($product)) {
            $this->Flash->success(__('The product has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('product', 'artist'));
    $this->set('_serialize', ['product']);
}

保存失败后调试实体:

object(App\Model\Entity\Product) {

    'new' => true,
    'accessible' => [],
    'properties' => [
        'artist' => object(App\Model\Entity\Artist) {

            'new' => false,
            'accessible' => [
                'photo' => true,
                'name' => true,
                'interview' => true
            ],
            'properties' => [
                'id' => (int) 5,
                'name' => 'Hello',
                'interview' => 'Hello'
            ],
            'dirty' => [],
            'original' => [],
            'virtual' => [],
            'errors' => [],
            'repository' => 'Artists'

        },
        'photo' => [
            'name' => '10714569_10152447024309147_3742856299050670367_o.jpg',
            'type' => 'image/jpeg',
            'tmp_name' => '/tmp/phpTtqrXR',
            'error' => (int) 0,
            'size' => (int) 235835
        ],
        'name' => 'Nataliee',
        'price' => (float) 200000000,
        'reference' => '000'
    ],
    'dirty' => [
        'artist' => true,
        'photo' => true,
        'name' => true,
        'price' => true,
        'reference' => true
    ],
    'original' => [],
    'virtual' => [],
    'errors' => [
        'artist_id' => [
            '_required' => 'This field is required'
        ]
    ],
    'repository' => 'Products'

}

1 个答案:

答案 0 :(得分:0)

好吧,你希望设置artist_id外键值,但实际上你那样做,所以这是预期的行为。

正在做什么,是为artist字段设置实体,但这不会以任何方式影响验证/表规则,它们仅适用于传递给patchEntity()调用的数组数据,在您的情况下,它们似乎需要artist_id字段。

因此,要么在数据中设置artist_id字段,就像

一样
$this->request->data['artist_id'] = $artist->id;
$product = $this->Products->patchEntity(/* ... */);
// ...

或更改您的验证/表规则,以便针对此特定操作,不需要artist_id字段,例如使用不同的验证集。

另见