简体   繁体   English

CakePHP多模型关联

[英]CakePHP Multiple Model association

I am confused with the CakePHP 2.x doc Model Association So need a little help over here to connect and find contains in result. 我对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

Need result like 需要结果如

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

I tried with $belongsTo and also with $hasAndBelongsToMany in DealsDealAttributes of all three Deal, DealAttribute, DealAttributeOption but didn't get the contains. 我试着用$belongsTo ,并与$hasAndBelongsToManyDealsDealAttributes三者的Deal, DealAttribute, DealAttributeOption但没有得到包含。 Now i want if i find any Deal then all the associated models will comes in contains. 现在我想要,如果我找到任何交易,那么所有相关的模型将包含。 How do i set up the Models association? 我如何设置模型关联?

It looks like your model associations should be set up something like this:- 看起来您的模型关联应该像这样设置: -

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

}

You will need to set the foreign key for the DealAttributeOption association in the DealsDealAttribute model as you've broken from CakePHP's naming convention (it should ideally be deal_attribute_option_id ). 您需要在DealsDealAttribute模型中为DealAttributeOption关联设置外键,因为您已经从CakePHP的命名约定中deal_attribute_option_id (理想情况下应该是deal_attribute_option_id )。

Update 更新

Then to retrieve a deal with the associated records you can use contain to retrieve the relevant models like this:- 然后检索与您可以使用的相关记录的交易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