我有一个 CakePHP 模型“Person”,它从 mysql View 加载其数据(public $useTable = 'people_rel';
,people_rel 是 View )。
该 View 将一些数据连接到表“people”。
View 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`)))
表 prefix_people:
列region_id、district_id和country_id在此模型中是只读的,它们可以在模型Outpost、Region和District中进行编辑。
问题是我无法保存模型,因为它是从 View 加载的。
我想从 View 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:
一个非常相似的解决方案是有效的。请参阅下面的答案。
最佳答案
根据 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');
}
关于php - CakePHP:保存从 MySQL View 加载的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568819/