簡體   English   中英

CakePHP多模型關聯

[英]CakePHP Multiple Model association

我對CakePHP 2.x doc 模型關聯感到困惑所以需要一點幫助來連接並查找包含在結果中。 在此輸入圖像描述

Deal Table > id | title
DealAttribute Table (has options) > id | title
DealAttributeOption Table (belongs to DealAttribute) > id | title | deal_attribute_id
DealsDealAttributes Table > id | deal_id | deal_attribute_id | option_id

需要結果如

Deal [
    id, title
    DealsDealAttributes [
        id, deal_id, deal_attribute_id, option_id
        DealAttribute [
            title
        ]
        DealAttributeOption [
            title
        ]
    ]
]

我試着用$belongsTo ,並與$hasAndBelongsToManyDealsDealAttributes三者的Deal, DealAttribute, DealAttributeOption但沒有得到包含。 現在我想要,如果我找到任何交易,那么所有相關的模型將包含。 我如何設置模型關聯?

看起來您的模型關聯應該像這樣設置: -

class Deal extends AppModel {

    public $belongsTo = [
        'User'
    ];

    public $hasMany = [
        'DealsDealAttribute'
    ];

}

class DealsDealAttribute extends AppModel {

    public $belongsTo = [
        'Deal',
        'DealAttribute',
        'DealAttributeOption' => [
            // Foreign key breaks naming convention so needs setting manually
            'foreignKey' => 'option_id'
        ]
    ];

}

class DealAttribute extends AppModel {

    public $belongsTo = [
        'User'
    ];

    public $hasMany = [
        'DealsDealAttribute'
    ];

}

class DealAttributeOption extends AppModel {

    public $hasMany = [
        'DealsDealAttribute'
    ];

}

您需要在DealsDealAttribute模型中為DealAttributeOption關聯設置外鍵,因為您已經從CakePHP的命名約定中deal_attribute_option_id (理想情況下應該是deal_attribute_option_id )。

更新

然后檢索與您可以使用的相關記錄的交易contain以檢索相關的模型,如下所示: -

$result = $this->Deal->find('first', [
    'contain' => [
        'DealsDealAttribute' => [
            'DealAttribute',
            'DealAttributeOption'
        ]
    ],
    'conditions' => [
        'Deal.id' => $id
    ]
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM