我是 datamapper orm 的新手,所以首先我决定为它创建一个模型生成器,以便以后可以轻松地生活。
首先,我创建了一个干净的 ci-2 文件夹。在控制器/welcome.php 中我写了
public function index()
{
$this->output->enable_profiler(TRUE);
$this->load->helper('inflector');
$this->load->helper('file');
echo "<pre>";
//list alll tables in database
$tables = $this->db->list_tables();
//grap all relations for database 'clinic-master'
$relations=$this->db->query("SELECT table_name, column_name,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.key_column_usage
WHERE referenced_table_schema = 'clinic-master'
ORDER BY table_name, column_name");
///looping tables
foreach ($tables as $table){
$x=$this->load->view('db',['table'=>$table,'fields'=>$this->db->list_fields($table)
,'relations'=>$relations],TRUE);
if(write_file("./application/models/dm/$table.php", $x))
echo "<hr><h1>$table</h1><code>$x</code>";
else
echo "<hr><h1>$table</h1><code>Failed to write file</code>";
}
}
和views/db.php 包括
<?$t=singular($table);echo"<?php";?>
class <?=$t?> extends DataMapper {
public $table = '<?=$table?>';
/*
<?print_r($relations->result());?>
*/
public $has_one = array();
public $has_many = array();
var $validation = array(
<?$x='';foreach($fields as $f){
$x.="'$f' => array(
'rules' => array('required'),
'label' => '<?=$f?>'
),";
}
echo trim($x,',');
?>
);
public $default_order_by = array('id' => 'desc');
// Optionally, don't include a constructor if you don't need one.
function __construct($id = NULL)
{
parent::__construct($id);
}
// Optionally, you can add post model initialisation code
function post_model_init($from_cache = FALSE)
{
}
}
/* End of file <?=$t?>.php */
/* Location: ./application/models/<?=$t?>.php */
现在我坚持如何回显 has_one 和 has_many !
这是我从 $relations 查询中得到的示例。
示例第一行显示说库存有一个诊所参考表诊所,而表诊所也有很多库存..(模型诊所,库存)
所以我循环了 $relations 并以表 inventroy 为例(前 2 行)是
public $has_one = array(
'clinic' => array(
'class' => 'clinic',
'other_field'=>'clinic',
join_other_as=>'id'
),
'code' => array(
'class' => 'inventory_item',
'other_field'=>'code',
join_other_as=>'id'
)
);
架构::
inventroy:id,code(fk),clinic(fk),amount
clinics : id,name
inventory_item:id,name,min_amount,etc....
code->inventory_item.id
clinic->clinics.id
问题
- 除了 class 之外,我还应该在 $has_one 数组中包含什么以确保它有效?
- 有什么已经存在的东西可以完成这项工作吗?
- 除了wanwizard guide之外,还有其他人使用 datamapper 解释高级关系的任何其他来源吗?因为我不能很好地理解它,特别是它只包含代码而没有可比较的表模式。