CakePHP如何保存manytomany

时间:2014-11-04 23:21:52

标签: cakephp many-to-many cakephp-appmodel

我有以下视图,用于向产品添加属性。

echo $this->Form->create('Product', array('role' => 'form'));
echo $this->Form->input('ProductProperty.Property', array(
    'multiple' => 'multiple',
    'type' => 'select',
));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Submit);

我必须在产品模型上执行哪些操作才能调用Properties和ProductProperties? ProductProperty是Product和Property表的映射模型。

array(
    'ProductProperty' => array(
        'Property' => array(
            (int) 0 => '4',
            (int) 1 => '5'
        )
    ),
    'Product' => array(
        'id' => '1'
    )
)

我收到以下错误:

Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: 
a foreign key constraint fails (`product_properties`, CONSTRAINT `product_properties_id_fk2` FOREIGN KEY (`property_id`) REFERENCES `properties` (`id`))

SQL Query: INSERT INTO `product_properties` (`product_id`) VALUES (1)

2 个答案:

答案 0 :(得分:0)

在CakePHP中,多对多称为HABTM 它在食谱中:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm

您应该有2个模型,产品和属性,以及3个数据库表:产品,属性和products_properties。比定义关联,你就完成了。

答案 1 :(得分:-1)

尝试设置$this->Model->recursive = 1;