我有3个树状的连接表。它们的模式如下:
Member{
//Some column
}
Transactions{
member_id :: foreign key of member table
//Some other column
}
TransactionItems{
transaction_id :: foreign key of Transaction table
//Some other column
}
我定义这样的模型:
class Members extends AppModel {
public $primaryKey = 'id';
public $hasOne = array(
'Transactions' => array(
'className' => 'Transactions',
'foreignKey' => 'member_id',
'dependent' => true
)
);
}
class Transactions extends AppModel {
public $primaryKey = 'id';
public $belongTo = array('Members');
public $hasOne = array(
'TransactionItems' => array(
'className' => 'TransactionItems',
'foreignKey' => 'transaction_id',
'dependent' => true
)
);
}
class TransactionItems extends AppModel {
public $primaryKey = 'id';
public $belongTo = array('Transactions');
public $belongsTo = array(
'Transactions' => array(
'className' => 'Transactions',
'foreignKey' => 'transaction_id'
)
);
}
我有一个数据数组,我想保存到数据库中。我的计划是:
Array(
[Members] = [],//Array
[Transactions] = [],//Array
[TransactionItems] = []//Array
)
问题在于,每当我运行$this->Members->saveAll($data)
时。它将数据保存在“会员和交易”表中。但是不要在TransactionItems表中创建数据。我想一次保存所有三个表。
任何帮助将不胜感激。
答案 0 :(得分:2)
第二级(及以上)关联必须嵌套,即数据结构必须为:
array(
'Members' => array(),
'Transactions' => array(
'TransactionItems' => array()
)
)
有点尴尬,但这就是它在2.x中的工作方式。读取数据时始终可以引用返回的结构,保存时必须保持相同。
此外,您必须将deep
选项设置为true
,以便能够保存第二级及以上的关联(默认情况下仅保存第一级关联):
$this->Members->saveAll($data, array('deep' => true));
另请参见