我想在CakePHP 3.0中使用belongsToMany-through關聯時設置使用的外鍵。指定在belongsToMany-through關聯中的外鍵
考慮下面兩個表:
實體:ID,標題
鏈接:ID,from_id,to_id,additional_information
我使用額外的,因爲belongsToMany,通過協會我需要在直通表中存儲信息。
下面是這兩個表類:
class LinksTable extends AppTable
{
public function initialize(array $config) {
parent::initialize($config);
$this->belongsTo('FromEntities', [
'className' => 'Entity',
'foreignKey' => 'from_id'
]);
$this->belongsTo('ToEntities', [
'className' => 'Entity',
'foreignKey' => 'to_id'
]);
}
}
class EntitiesTable extends AppTable
{
public function initialize(array $config) {
parent::initialize($config);
$this->belongsToMany('Entities', [
'through' => 'Links'
]);
}
}
但當然CakePHP中試圖加入表使用默認的外鍵entity_id
,這是不正確的。
如何定義用於連接EntitiesTable類中的表的外鍵?
編輯:爲了完整起見,在這裏試圖用$this->Entities->findById(1)->contain('Entities');
協會獲取實體時是錯誤信息和生成的查詢。
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Links.entity_id' in 'field list'
SELECT Links.entity_id AS `Links__entity_id`, Links.id AS `Links__id`, Links.from_id AS `Links__from_id`, Links.to_id AS `Links__to_id`, Links.type AS `Links__type`, Links.role AS `Links__role`, Entities.id AS `Entities__id`, Entities.type AS `Entities__type`, Entities.title AS `Entities__title`, Entities.user_id AS `Entities__user_id`, Entities.created AS `Entities__created` FROM entities Entities INNER JOIN links Links ON Entities.id = (Links.entity_id) WHERE Links.entity_id in (:c0)
有在我剝離出來的代碼示例上面,如果你想知道生成的查詢一些附加字段。