如何在 CakePHP 2 中为连接表的 3 树保存数据
How To Save Data in CakePHP 2 for 3 tree like connected tables
我有 3 棵像相连的树 table。他们的架构如下:
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)
。它在 Member 和 Transactions table 中保存数据。但不要在 TransactionItems table 中创建数据。我想一次保存所有 3 tables。
任何帮助将不胜感激。
二级(及以上)关联必须是嵌套的,即数据结构需要是:
array(
'Members' => array(),
'Transactions' => array(
'TransactionItems' => array()
)
)
有点尴尬,但这就是它在 2.x 中的工作方式。读取数据时可以随时引用返回的结构,保存时需要相同。
此外,您必须将 deep
选项设置为 true
才能保存二级及以上关联(默认情况下仅保存一级关联):
$this->Members->saveAll($data, array('deep' => true));
另见
我有 3 棵像相连的树 table。他们的架构如下:
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)
。它在 Member 和 Transactions table 中保存数据。但不要在 TransactionItems table 中创建数据。我想一次保存所有 3 tables。
任何帮助将不胜感激。
二级(及以上)关联必须是嵌套的,即数据结构需要是:
array(
'Members' => array(),
'Transactions' => array(
'TransactionItems' => array()
)
)
有点尴尬,但这就是它在 2.x 中的工作方式。读取数据时可以随时引用返回的结构,保存时需要相同。
此外,您必须将 deep
选项设置为 true
才能保存二级及以上关联(默认情况下仅保存一级关联):
$this->Members->saveAll($data, array('deep' => true));
另见