CakePHP:保存从 MySQL 视图加载的模型
Posted
技术标签:
【中文标题】CakePHP:保存从 MySQL 视图加载的模型【英文标题】:CakePHP: Save Model loaded from MySQL View 【发布时间】:2014-08-29 13:00:01 【问题描述】:我有一个 Cakephp 模型“Person”,它从 mysql 视图(public $useTable = 'people_rel';
,people_rel 是视图)加载其数据。
该视图将一些数据连接到表“人”。
视图prefix_people_rel:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `xxxxxxx`@`%`
SQL SECURITY DEFINER
VIEW `prefix_people_rel` AS
select
`prefix_people`.`id` AS `id`,
`prefix_people`.`username` AS `username`,
`prefix_people`.`first_name` AS `first_name`,
`prefix_people`.`last_name` AS `last_name`,
`prefix_people`.`email` AS `email`,
`prefix_people`.`password` AS `password`,
`prefix_people`.`status` AS `status`,
`prefix_people`.`outpost_id` AS `outpost_id`,
`prefix_outposts`.`region_id` AS `region_id`,
`prefix_regions`.`district_id` AS `district_id`,
`prefix_districts`.`country_id` AS `country_id`
from
(((`prefix_people`
left join `prefix_outposts` ON ((`prefix_people`.`outpost_id` = `prefix_outposts`.`id`)))
left join `prefix_regions` ON ((`prefix_outposts`.`region_id` = `prefix_regions`.`id`)))
left join `prefix_districts` ON ((`prefix_regions`.`district_id` = `prefix_districts`.`id`)))
表前缀_人:
region_id、district_id 和 country_id 列在此模型中是只读的,它们在模型 Outpost、Region 和 District 中进行编辑。 问题是我无法保存模型,因为它是从视图中加载的。 我想从 people_rel 视图中加载数据并将它们保存到 people 表中。我怎样才能做到这一点? (我使用的是 CakePHP 2.5.3,一旦稳定版可用,我想升级到 3)
非常感谢!
编辑: 这没有帮助:模型人:
public function beforeSave($options = array())
// ... Password hashing ...
$this->useTable = 'people';
return true;
public function afterSave($created, $options = array())
$this->useTable = 'people_rel';
编辑 2: 一个非常相似的解决方案有效。请参阅下面的答案。
【问题讨论】:
不清楚是否使用同型号People
读取和保存。但如果是的话,你有没有试过在beforeSave
开头更改表别名(和数据库表),并在afterSave结尾改回people_rel
?我误解你的问题了吗?
我正在从“people_rel”视图中读取数据,并希望将更改写入“people”表,但这一切都是从“Person”模型完成的。我用 before- 和 afterSave 尝试了你的想法(请参阅我的编辑),但没有奏效。
根据您的想法,我找到了解决方案。我会在下面添加它。谢谢!
太好了!如果我必须做类似的事情,会记住这一点。
【参考方案1】:
根据 Nunser 的想法,我找到了解决方案。 在模型中,我添加了 beforeSave() 和 afterSave():
public function beforeSave($options = array())
//$this->useTable = 'people'; <= Does not work
$this->setSource('people'); // Works
return true;
public function afterSave($created, $options = array())
//$this->useTable = 'people_rel'; <= Does not work
$this->setSource('people_rel'); // Works
删除对象所需:
public function beforeDelete($cascade = true)
$this->setSource('people');
return true;
public function afterDelete()
$this->setSource('people_rel');
【讨论】:
以上是关于CakePHP:保存从 MySQL 视图加载的模型的主要内容,如果未能解决你的问题,请参考以下文章
CakePHP 如何在一个视图中显示来自三个相关模型的数据?