Cakephp:使用`saveAssociated()`时如何将`parent_id`保存到基于树的模型中?
Posted
技术标签:
【中文标题】Cakephp:使用`saveAssociated()`时如何将`parent_id`保存到基于树的模型中?【英文标题】:Cakephp: How to save `parent_id` into a Tree based Model deeply when using `saveAssociated()`? 【发布时间】:2012-10-25 16:04:40 【问题描述】:我的数据库结构:
CREATE TABLE IF NOT EXISTS `pos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`alias` varchar(255) NOT NULL,
`model` varchar(255) NOT NULL,
`foreign_key` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `alias` (`alias`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `psos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0',
`po_id` int(11) NOT NULL,
`lft` int(11) NOT NULL DEFAULT '0',
`rght` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
我的模型结构:
class Po extends Model
public $name = 'Po';
public $useTable = 'pos';
public $cacheQueries = false;
public $hasMany = array(
'Pso' => array(
'className' => 'Pso',
'foreignKey' => 'po_id',
'dependent' => true,
),
'Puso' => array(
'className' => 'Puso',
'foreignKey' => 'po_id',
'dependent' => true,
),
);
class Pso extends Model
public $name = 'Pso';
public $useTable = 'psos';
public $cacheQueries = false;
public $actsAs = array(
'Tree',
);
public $belongsTo = array(
'Parent' => array(
'className' => 'Pso',
'foreignKey' => 'parent_id',
),
'Po' => array(
'className' => 'Po',
'foreignKey' => 'po_id',
),
);
public $hasMany = array(
'Children' => array(
'className' => 'Pso',
'foreignKey' => 'parent_id',
),
);
我的保存关联测试代码:
$Po->saveAssociated(array(
'Po' => array(
'alias' => 'teste'.uniqid(),
),
'Pso' => array(
'parent_id' => 2,
),
));
生成的 PSO 保存行:
array('id'=>4,'parent_id'=>0,'po_id'=>4,'lft'=>7,'rght'=>8)
预期 PSO 已保存行:
array('id'=>4,'parent_id'=>2,'po_id'=>4,'lft'=>7,'rght'=>8)
【问题讨论】:
【参考方案1】:这样解决:
$Po->saveAssociated(array(
'Po' => array(
'alias' => 'teste'.uniqid(),
),
'Pso' => array(
'parent_id' => array(
'parent_id' => 2,
),
),
));
【讨论】:
以上是关于Cakephp:使用`saveAssociated()`时如何将`parent_id`保存到基于树的模型中?的主要内容,如果未能解决你的问题,请参考以下文章
Cakephp saveAssociated 和 SaveAll Nothing 正常工作
cakephp 模型 saveAssociated 错误 - 不能将字符串偏移量用作数组
CakePHP如何在一个saveAll中不知道外键的情况下创建hasMany数据?