2014-08-29 46 views
0

我有一个CakePHP模型“Person”,它从mysql-view加载其数据(public $useTable = 'people_rel';,people_rel是视图)。
视图将一些数据连接到表'人'。CakePHP:从MySQL视图加载保存模型

视图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: The table prefix_people

列REGION_ID,district_id和COUNTRY_ID是只读的,在这个模型中,他们在模型编辑前哨,地区和区域。
问题是我无法保存模型,因为它是从视图中加载的。
我想从视图中加载数据people_rel并将它们保存到表格中。我怎样才能做到这一点? (我使用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:
一个非常类似的解决方案工作。请参阅下面的答案。

+1

它,如果你使用的是相同的模型'人们尚不清楚'阅读并保存。但是,如果是这样,是否尝试在'beforeSave'的开始处更改表别名(和数据库表),并在afterSave结束时将其更改回'people_rel'?我误解你的问题吗? – Nunser 2014-08-29 13:18:30

+0

我正在读取'people_rel'视图中的数据,并且想要将更改写入表'people',但是这些都是从Model'Person'完成的。我用before-和afterSave尝试了你的想法(参见我的编辑),但它不起作用。 – 2014-08-29 13:26:02

+0

根据你的想法,我找到了一个解决方案。我将在下面添加它。谢谢! – 2014-08-29 13:31:03

回答

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'); 
}