การระบุคีย์ต่างประเทศในการเชื่อมโยงเป็นของ BelongToMany

ฉันต้องการตั้งค่าคีย์ต่างประเทศที่ใช้เมื่อใช้การเชื่อมโยงเป็นของ BelyToMany ใน CakePHP 3.0

พิจารณาสองตารางต่อไปนี้:

เอนทิตี: id, ชื่อ
ลิงก์: id, from_id, to_id, ข้อมูลเพิ่มเติม

ฉันกำลังใช้การเชื่อมโยงของ belyToMany-through เนื่องจากมีข้อมูลเพิ่มเติมที่ฉันต้องเก็บไว้ในตารางผ่าน

นี่คือคลาส Table สองคลาส:

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

ข้อผิดพลาด: SQLSTATE [42S22]: ไม่พบคอลัมน์: 1054 คอลัมน์ที่ไม่รู้จัก 'Links.entity_id' ใน 'รายการฟิลด์'

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)

มีฟิลด์เพิ่มเติมบางฟิลด์ในการสืบค้นที่สร้างขึ้นซึ่งฉันได้ดึงออกจากตัวอย่างโค้ดด้านบน ในกรณีที่คุณสงสัย


person Lars Ebert    schedule 06.10.2015    source แหล่งที่มา


คำตอบ (1)


หลังจากขุดผ่านกรณีทดสอบบางกรณี ฉันพบคำตอบใน สิ่งนี้ ทดสอบ.

เมธอด belongsToMany มีตัวเลือกที่ไม่มีเอกสาร targetForeignKey ดังนั้นคลาส EntitiesTable ควรมีลักษณะดังนี้:

class EntitiesTable extends AppTable
{
    public function initialize(array $config) {
        parent::initialize($config);

        $this->belongsToMany('LinkedEntities', [
            'className' => 'Entities',
            'through' => 'Links',
            'foreignKey' => 'from_id',
            'targetForeignKey' => 'to_id'
        ]);
    }
}

ตอนนี้ฉันสามารถเข้าถึงเอนทิตีที่เชื่อมโยงโดยใช้ $this->Entities->findById(1)->contain('LinkedEntities');

person Lars Ebert    schedule 06.10.2015