2017-03-03 101 views
0

我有以下表格:cars,car_types和car_methods。我的問題是關係。這輛車有一種類型和一種方法。CakePHP 3表關係

我的目標是展示汽車和他的附件「車型」和「car_method」。

汽車表:

id - type_id - method_id 

Car_types表:

id - type 

Car_methods表:

id - method 

如何CA n個I設置這裏面我的模型表,這樣我可以在我的控制器像裏面做:

$this->Cars->CarTypes->find('all'); 

我嘗試如下,但它會給出一個無關聯的錯誤:

汽車模型:

class CarsTable extends Table { 
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' 
    ]); 

    $this->hasOne('CarMethods', [ 
     'className' => 'Cars.CarMethods', 
     'foreignKey' => 'method_id', 
     'propertyName' => 'method' 
    ]); 
} 
} 

CarTypes型號:

class CarTypesTable extends Table { 

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

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

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

CarMethots型號:

class CarMethodsTable extends Table { 

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

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

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

您是否嘗試過的文檔? https://book.cakephp.org/3.0/en/orm/associations.html – burzum

+0

是的,我試過文檔,但我不太明白。我已經爲你添加了代碼。 – CodeWhisperer

+0

它有許多類型和方法的汽車。您可以像現在一樣指向表格本身的類型和方法。閱讀本書中的教程或關於如何關聯日期的一些通用SQL教程。:) – burzum

回答

2

你的最後兩個關係是錯誤的,這裏是好的

CarTypes型號:

public function initialize(array $config) { 
    $this->hasMany('Cars', [ //A CarType hasMany Cars 
     'foreignKey' => 'type_id' 
    ]); 
} 

CarMethods型號:

public function initialize(array $config) { 
    $this->hasMany('Cars', [ //A CarMethod hasMany Cars 
     'foreignKey' => 'method_id' 
    ]); 
} 

控制LER行動

併爲您的查詢,這兩個關係添加到包含選項:

//Get all cars with type and method 
$this->Cars->find('all', 
    [ 
     'contain' => ['CarTypes', 'CarMethods'] 
    ] 
); 
+0

我已經用你的例子更新了我的問題中的模型,但我仍然有一個(無法導出對象:汽車與CarTypes和CarMethods沒有關聯)}。 – CodeWhisperer

+1

我已經解決了。我的模型的名稱空間沒有鏈接到我的插件。有時問題很簡單。 :) 感謝幫助! – CodeWhisperer

0

The belongsTo association is a natural complement to the hasOne and hasMany associations: it allows us to see the data from the other direction.

belongsTo: the current model contains the foreign key.

如果你在你的表的外鍵,則該表將屬於相關聯的表。所以,你的情況:

public function initialize(array $config) { 
    $this->belongsTo('CarTypes', [ 
     'foreignKey' => 'type_id', 
     'joinType' => 'LEFT' 
    ]); 

    $this->belongsTo('CarMethods', [ 
     'foreignKey' => 'method_id', 
     'joinType' => 'LEFT' 
    ]); 
} 

這之後您可以使用$this->Cars->CarTypes->find('all');