2017-03-03 17 views
1

私は2つのテーブルを持っています:車とcar_types。車 "hasOne"タイプとタイプ "hasMany"車。私のモデルでこの制約を定義しましたが、以下のようなエラーメッセージを表示せずにコントローラまたはビュー内の値を読み取るにはどうすればよいですか?CakePHP 3 - 1054列が見つかりません

MySQLエラーメッセージ:

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

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

車のテーブル::

id - type_id - method_id 

Car_typesテーブル

"Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CarTypes.type_id' in 'on clause'"

私はCarsController内でこれを行うこのエラーを得ました:

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

'CarTypes'のための' Cars.CarTypes'、 –

+0

を変更しても同じエラーが発生します。 – CodeWhisperer

答えて

2

親テーブル内のレコード(CarTypesCarsテーブルに(複数の子レコードを持つこと)、その関係はhasManyのように良いです。ただし、子レコード(Cars表内)は、が1つのCarTypeに属し、CarTypeを持たない場合はになる必要があります。

本質的に、hasは親 - >子関係であり、belongsは子 - >親関係です(詳細はcakephp documentation on associationsを参照)。だから、belongsToCars変更hasOneに:

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はないCarTypesの表に、Carsテーブルにtype_idフィールドを探します。

関連する問題