【问题标题】:Template only has access to ID's of "foreign" table模板只能访问“外国”表的 ID
【发布时间】:2018-12-28 17:30:23
【问题描述】:

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

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

+----------------------------------+
|           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');
    }
    ...
}

产品控制器

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]);

【问题讨论】:

  • 这里重要的代码不是 add 函数,而是视图(也可能是索引,取决于您的要求)。不过,很明显您不是 containing 控制器中的关联模型,或引用视图中的关联数据。

标签: php cakephp controller associations


【解决方案1】:

我不得不将我的 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]);

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多