Cake PHP HABTM与同一模型的关系

时间:2013-05-01 14:22:09

标签: cakephp

我有一个product表和products_relateds表。这包含2个对产品的引用(product_id和related_id)

我正在尝试为此设置HABTM关系,就像我的产品型号

一样
public $hasAndBelongsToMany = array(
        'Related' => array(
            'className' => 'Product',
            'joinTable' => 'products_relateds',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'related_id',
            'unique' => 'keepExisting',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        )
    );

这看起来不错吗?我需要创建相关模型吗? 我没有错误,并且当这种关系到位时,查看产品页面将无法加载

1 个答案:

答案 0 :(得分:0)

该代码没问题,您的错误必须在其他地方。使用$this->Product->findBy(1)应该返回如下内容:

array(
    'Product' => array(
        'id' => '1',
        'name' => 'Test 1'
    ),
    'Related' => array(
        0 => array(
            'id' => '2',
            'name' => 'Test 2',
            'ProductsRelated' => array(
                'id' => '3',
                'product_id' => '1',
                'related_id' => '2'
            )
        ),
        1 => array(
            'id' => '3',
            'name' => 'Test 3',
            'ProductsRelated' => array(
                'id' => '1',
                'product_id' => '1',
                'related_id' => '3'
            )
        )
    )
)