CakePHP 3 - 1054未找到列

时间:2017-03-03 13:40:45

标签: mysql cakephp cakephp-3.0

我有两张桌子:汽车和car_types。汽车“hasOne”类型和类型“hasMany”汽车。我已经在我的模型中定义了这些约束,但是如何在不获取如下错误消息的情况下读取控制器或视图中的值?

Mysql错误消息:

  

“错误:SQLSTATE [42S22]:找不到列:1054未知列   'on clause'“

中的'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

CarTypes型号:

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

1 个答案:

答案 0 :(得分:2)

父表(CarTypes)中的记录可能有多个子记录(在Cars表中),因此该关系可以正常为hasMany。但是,子记录(在Cars表格中)应该属于一个CarType,而不是CarType

基本上,has是父母 - >儿童关系,而belongs是孩子 - >父关系(详见cakephp documentation on associations)。因此,在Cars更改hasOnebelongsTo

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将在type_id表中查找Cars字段,而不是在CarTypes表中。