強化GroceryCRUD的join功能

強化GroceryCRUD的join功能

grocerycrud是一個可以快速建立CRUD頁面和功能的一個好工具,但是他的join寫的實在有點死板板,不過好在我們還是可以有一些方法可以解決掉這個問題
首先建立一個model $codeigniterRoot/application/models/$modelName_model.php,下面是程式的內容

<?php
class Crud_classes_students_join extends grocery_CRUD_Model
{
	function get_list()
	{
		if($this->table_name === null)
			return false;

		$select = "{$this->table_name}.*";

		// 在這裡加入我們要額外select的欄位
		// $select .= ", user_log.created_date, user_log.update_date";

		if(!empty($this->relation))
			foreach($this->relation as $relation)
			{
				list($field_name , $related_table , $related_field_title) = $relation;
				$unique_join_name = $this->_unique_join_name($field_name);
				$unique_field_name = $this->_unique_field_name($field_name);

				if(strstr($related_field_title,'{'))
					$select .= ", CONCAT('".str_replace(array('{','}'),array("',COALESCE({$unique_join_name}.",", ''),'"),str_replace("'","\\'",$related_field_title))."') as $unique_field_name";
				else
					$select .= ", $unique_join_name.$related_field_title as $unique_field_name";

				if($this->field_exists($related_field_title))
					$select .= ", {$this->table_name}.$related_field_title as '{$this->table_name}.$related_field_title'";
			}

		$this->db->select($select, false);

		// 這裡寫上我們需要的join語法
		$teacherID = $this->session->userdata('userID');
		$this->db->join('teacher_student',"users.user_id=teacher_student.student_id and teacher_student.teacher_id=$teacherID");
		$obj = $this->db->get($this->table_name);
		$results = $obj->result();

		return $results;
	}
}

接下來在$codeigniterRoot/application/controllers/$controllerName

$crud = new grocery_CRUD();
$crud->set_model($modelName); // 這裡就是把我們剛剛建立的model載入進來
$crud->set_theme('datatables');
$crud->set_table('users');
$crud->set_subject('student');

這樣就可以讓GroceryCRUD根據我們特殊需求去做join,不會再受限於原本的架構了

Post Tags :

阿維

阿維雜記本的偷懶維護者