2014-08-29 26 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'); 
}