我目前正在研究我的mvc框架(使用PHP)。我看到CakePHP有能力使用「belongsTo」和「hasMany」特性。我正在嘗試創建自己的功能,並遇到問題。假設我們有預約表(id,where,date,year_id)和年份表(id,year)。我知道這個例子可以在沒有問題的情況下用一張表完成,但這只是一個例子。如何讓模型「hasMany」和「belongsTo」? (像cakePHP一樣)
class appointment_model extends model{
public $_belongs_to= array('table'=>'year','field_connector'=>'year_id');
public $one_value;
}
......
class year_model extends model{
public $_has_many= array('table'=>'appointment','field_connector'=>'year_id');
public $many_values;
}
....
class model{
private function select($query=null){
if(!$query)die("Query cannot be null. Line num: " . __LINE__);
$results = $this->_db->mysql_select($query);
if(count($results)==1){
$one = $this->initialize($results[0]);
$this->_do_for_other_tables($one);
return $one;
}elseif(count($results)>1){
$returns = array();
foreach($results as $result){
$one = $this->initialize($result);
$returns[] = $this->_do_for_other_tables($one);
}
return $returns;
}else{
return null;
}
}
private function _do_for_other_tables(&$one, $rec=1){
if(property_exists($this, 'many_values')){
if(!empty($one->many_values))return;
$many = functions::load_model($this->_has_many["table"]);
$res = $many->find_by($this->_has_many["field_connector"], $one->id);
$one->many_values = $res;
}
elseif(property_exists($this, 'one_value')){
if(!empty($one->_belongs_to))return;
$only_one = functions::load_model($this->_belongs_to["table"]);
$field = $this->_belongs_to['field_connector'];
$res = $only_one->find_by('id', $one->$field);
$one->one_value = $res;
}
}
}
基本上這裏所發生的是,我進入無限循環。任何建議如何解決這個問題?如果我需要更多地解釋它,就說出來。
謝謝:)。
你爲什麼又重新發明了輪子?學說開箱即用! – Francesco
@Francesco:這不是因爲你不想知道它是如何在引擎蓋下工作的,別人也不會。我自己構建了大量的框架來滿足我的需求,因爲他們每個人都不適合我。 Vizualni在這裏可能是同樣的東西... –