我想在Codeigniter中的模型中使用递归,并且对于我应该声明要在递归函数中使用的全局变量的位置感到困惑。
我正在尝试显示按地理分类排序的产品目录。递归是必要的,因为地理数据库是一个层次树,一个地方可以有儿子,孙子,曾孙等(例如:伦敦是英国的儿子,英国的儿子,英国的儿子,欧洲的儿子)。
在递归结束时,我想返回变量$arrCatalog
,它将保存所有产品。所以我的另一个问题是如何最终返回该变量?
这是我的代码(尚未测试,因为我不知道如何处理全局变量):
class Catalogs_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function getCatalog($place_id, $prod_type)
{
$sql =
"SELECT id, heb_name, type FROM places p
INNER JOIN places_relations r ON p.id = r.son
WHERE father = ?
ORDER BY sort_name";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 =
"SELECT code, heb_title, price, place_id FROM products
INNER JOIN products_places ON prod_code=code
WHERE place_id = ? AND prod_type = ?";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$arrCatalog[] = $product; // $arrCatalog is the global variable I don't know where to declare and how to return.
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
}
答案 0 :(得分:0)
将您的变量传递给当前对象($ this),然后您可以将其传递给模型或将其传递给控制器。
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
public function __construct() {
parent::__construct();
}
function getCatalog($place_id, $prod_type) {
$sql = "SELECT ...";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 = "...";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$this->arrCatalog[] = $product;
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
你的控制器:
$this->catalogs_model->getCatalog(2, 'hebBook');
$data['data_rows'] = $this->catalogs_model->arrCatalog;
测试,改变你的模型......
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
// add these variables for testing ....
private $greeting = 'Hello'; // notice this is private? You cannot access this from your controller but you can from anywhere within the Catalogs_model class.
public $output = ''; // public
public $string = null; // public
// your existing code ...
function hello ()
{
$this->output = $this->greeting;
}
function hello_string ()
{
if($this->string)
{
$this->output = $this->greeting.' '.$string;
}
}
} // end class
现在在你的控制器中测试
$this->catalogs_model->hello(); // runs the hello function which sets the model->output
echo $this->catalogs_model->output; // echos 'Hello'
echo '<br />'; // just so the output stands apart in your browser.
$this->catalogs_model->string = 'World!';
$this->catalogs_model->hello_string();
echo $this->catalogs_model->output; // echos Hello World!