我有4个模型,Application
,Accommodation
,Invoice
和InvoiceItem
Invoice
,Application
和Accommodation
所有人都有InvoiceItem
InvoiceItem
belongsTo Application
,Accommodation
和Invoice
所有这一切的目的是使Invoice
(来自InvoiceItem
模型)的订单项可以与Accommodation
或{{1}相关联} Application
取决于InvoiceItem.foreign_id
是InvoiceItem.class
还是Accommodation
据我所知,这被称为多态关联。
不幸的是,当我使用递归设置为3(或设置为-1并使用containsable中指定的相应字段)执行Application
时,我收到此MySQL错误:
$this->Invoice->find('all');
我不明白为什么Cake会尝试添加Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'InvoiceItem.class' in 'where clause'
SQL Query: SELECT `Application`.`id`, `Application`.`name`,
`Application`.`created`, `Application`.`updated` FROM `applications`
AS `Application` WHERE `Application`.`id` = 3786 AND
`InvoiceItem`.`class` = 'Application'
作为条件而不为InvoiceItem.class
模型创建连接。
以下是我的模型(注意:为了便于阅读,我减少了每个字段的数量 - InvoiceItem
和Application
模型在现实中共享的字段非常少):
住宿模式
Accommodation
应用程序模型
CREATE TABLE `accommodations` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`updated` datetime NOT NULL,
PRIMARY KEY (`id`)
)
<?php
class Accommodation extends AppModel {
var $name = 'Accommodation';
var $hasMany = array(
'InvoiceItem' => array(
'className' => 'InvoiceItem',
'foreignKey' => 'foreign_id',
'conditions' => array('InvoiceItem.class' => 'Accommodation'),
)
);
}
?>
InvoiceItem模型
CREATE TABLE `applications` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`updated` datetime NOT NULL,
PRIMARY KEY (`id`)
)
<?php
class Application extends AppModel {
var $name = 'Application';
var $hasMany = array(
'InvoiceItem' => array(
'className' => 'InvoiceItem',
'foreignKey' => 'foreign_id',
'conditions' => array('InvoiceItem.class' => 'Application'),
)
);
}
?>
发票型号
CREATE TABLE IF NOT EXISTS `invoice_items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`class` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`foreign_id` int(10) unsigned NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
<?php
class InvoiceItem extends AppModel {
var $name = 'InvoiceItem';
var $belongsTo = array(
'Accommodation' => array(
'foreignKey' => 'foreign_id',
'conditions' => array('InvoiceItem.class' => 'Accommodation')
),
'Application' => array(
'foreignKey' => 'foreign_id',
'conditions' => array('InvoiceItem.class' => 'Application')
),
'Invoice' => array(
'className' => 'Invoice',
'foreignKey' => 'invoice_id',
),
);
}
?>
我正在使用CakePHP 2.4.0
答案 0 :(得分:0)
类InvoiceItem扩展AppModel,并且不绑定belongsTo。
class InvoiceItem extends AppModel {
var $name = 'InvoiceItem';
var $belongsTo = null
}
您可以在运行时根据内容
为InvoiceItem分配合适的belongsTo$this->InvoiceItem->bindModel(array( 'belongsTo' => array(...) ) )