【问题标题】:CakePHP 3 - 1054 Column not foundCakePHP 3 - 1054 未找到列
【发布时间】:2017-07-23 15:46:09
【问题描述】:

我有两个表:cars 和 car_types。汽车“hasOne”型和“hasMany”型汽车。我已经在我的模型中定义了这个约束,但是我怎样才能读取控制器或视图中的值而不会收到如下错误消息?

Mysql 错误信息:

“错误:SQLSTATE[42S22]:未找到列:1054 未知列 'on 子句'中的'CarTypes.type_id'"

当我在 CarsController 中执行此操作时出现此错误:

public function index() {
   $query = $this->Cars->find('all', ['contain' => [
        'CarTypes'
   ]]);

   debug($query->toArray());
}

汽车表:

id - type_id - method_id

Car_types 表:

id - type

车型:

 public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('car_types');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('Cars', [
            'foreignKey' => 'type_id'
        ]);
    }

车型:

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('cars');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasOne('CarTypes', [
            'className' => 'Cars.CarTypes',
            'foreignKey' => 'type_id',
            'propertyName' => 'type'
        ]);
    }    

【问题讨论】:

  • Cars.CarTypes换成CarTypes
  • 这将给出同样的错误。

标签: mysql cakephp cakephp-3.0


【解决方案1】:

父表(CarTypes)中的一条记录可能有多个子记录(Cars 表中),所以这种关系就像hasMany。但是,子记录(在Cars 表中)应该属于一个CarType,而不是CarType

本质上,has 是父-> 子关系,而belongs 是子-> 父关系(详见cakephp documentation on associations)。因此,在Cars 中将hasOne 更改为belongsTo

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('cars');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('CarTypes', [
            'className' => 'CarTypes',
            'foreignKey' => 'type_id',
            'propertyName' => 'type'
        ]);
    } 

在这种情况下,CakePHP 将在Cars 表中查找type_id 字段,而不是在CarTypes 表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2016-04-09
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2019-01-13
    相关资源
    最近更新 更多