【问题标题】:How To Save Data in CakePHP 2 for 3 tree like connected tables如何在 CakePHP 2 中为 3 个树状连接表保存数据
【发布时间】:2018-12-11 10:30:48
【问题描述】:

我有 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 表中创建数据。我想一次保存在所有 3 个表中。

任何帮助将不胜感激。

【问题讨论】:

    标签: php cakephp orm cakephp-2.0


    【解决方案1】:

    二级(及以上)关联必须嵌套,即数据结构需要:

    array(
        'Members' => array(),
        'Transactions' => array(
            'TransactionItems' => array()
        )
    )
    

    有点尴尬,但这就是它在 2.x 中的工作方式。读取数据时可以随时参考返回的结构,保存时需要保持一致。

    此外,您必须将deep 选项设置为true 才能保存二级及以上关联(默认情况下仅保存一级关联):

    $this->Members->saveAll($data, array('deep' => true));
    

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多