【问题标题】:cannot associate products and categories table in cakephp 3无法在 cakephp 3 中关联产品和类别表
【发布时间】:2017-12-06 18:13:57
【问题描述】:

我有一个表结构:

产品:

  1. products_id
  2. 产品名称
  3. product_price
  4. product_description
  5. category_id

分类:

  1. category_id
  2. 类别名称

有 2 种不同的表单可以分别添加和编辑产品和类别。我想关联这两个表,这样我就不必根据编辑表单下拉列表中的 category_id 搜索 category_name。 我已尝试关联它,但出现以下错误:

表“Cake\ORM\Table”未与“Categories”关联

class ProductsTable extends Table {
   public function initialize(array $config){
        $this->table('Products');
        $this->primaryKey('product_id');
       $this->belongsTo('Categories', ['foreignKey' => 'product_id']);

    }
}


class CategoriesTable extends Table {
  public function initialize(array $config){
     $this->table('Categories');
     $this->primaryKey('category_id');
      $this->hasMany('Products', ['foreignKey' => 'category_id']);
    }
}

查看:

  public function index()
    {
$this->set('categories', $this->Products->Categories->find('list', array('fields' => array('Categories.category_id'),'value'=>array('Categories.category_name'))));
}

请帮助解决我的问题。

【问题讨论】:

  • 在您的索引函数中检查$this->Products 的类型(get_class)。似乎它可能不是您期望的类型,而是一个通用的表对象。这可能指向文件命名问题或命名空间问题。
  • @GregSchmidt:它打印 Cake\ORM\Table。
  • ProductsController里面有index方法吗?检查文件名和文件夹。也许这个答案也适合你stackoverflow.com/a/21986180/2776508(即使是蛋糕2)

标签: php cakephp cakephp-3.0


【解决方案1】:

改变 $this->primaryKey('product_id'); 到 $this->primaryKey('products_id');

并添加 $this->displayField('category_name');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多