模板只能访问“外部”表的ID

时间:2018-12-28 17:30:23

标签: php cakephp controller associations

我一直在Cakephp网站上关注example,并对其进行修改,以使其对我的项目“有效”。

我有一个表,该表的列是另一个表的外键,但是我的模板仅填充了ID,而没有填充(外)表的其他列。如何在模板视图中访问“ categorieen.type”?

enter image description here

+----------------------------------+
|           PRODUCTEN              | 
+----------------------------------+
| productenid  (PK)                | 
| categorie    (FK)                | 
+----------------------------------+

+----------------------------------+
|           CATEGORIEEN            |
+----------------------------------+
| categorieid  (PK)                | 
| type                             | 
+----------------------------------+

ProductenTable

class ProductenTable extends Table {

    public function initialize(array $config){
        $this->belongsTo('Categorieen');
        $this->addBehavior('Timestamp');
    }
    ...
}

ProductenController

public function add() {
        $product = $this->Producten->newEntity();
        if ($this->request->is('post')) {
            $product = $this->Producten->patchEntity($product, $this->request->getData());

            if ($this->Producten->save($product)) {
                $this->Flash->success(__('Your product has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add your product.'));
        }

        $categorieen = $this->Producten->Categorieen->find('list');

        $this->set('product', $product);
        $this->set('categorieen', $categorieen);
    }

add.ctp

echo $this->Form->control('categorieen', ['options' => $categorieen]);

1 个答案:

答案 0 :(得分:0)

我必须将 add()更改为:

public function add() {
        $product = $this->Producten->newEntity();
        if ($this->request->is('post')) {
            $product = $this->Producten->patchEntity($product, $this->request->getData());

            if ($this->Producten->save($product)) {
                $this->Flash->success(__('Your product has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add your product.'));
        }

        $categorieen = $this->Producten->Categorieen->find('list', -----> CHANGED
            ['keyField' => 'categorieid', 'valueField' => 'type']
        );

        $this->set('product', $product);
        $this->set('categorieen', $categorieen);
    }

和我的 edit.ctp 发送至:

echo $this->Form->control('categorie', ['options' => $categorieen]);