controller.php
$data["category_products"] = $this->product_model->get_products_by_category_id();
model.php
//get products by category ID
public function get_products_by_category_id()
{
$lc_key = get_location_cache_key($this);
$key = "special_offers_lang_" . $this->selected_lang->id;
$result_cache = get_cached_data($this, $key, "pr");
if (!empty($result_cache)) {
if (!empty($result_cache[$lc_key])) {
return $result_cache[$lc_key];
}
} else {
$result_cache = array();
}
$this->build_query();
$this->db->where('products.category_id', 1);
$this->db->order_by('products.created_at', 'DESC')->limit(20);
$result = $this->db->get('products')->result();
$result_cache[$lc_key] = $result;
set_cache_data($this, $key, $result_cache, "pr");
return $result;
}
view.php
<?php foreach ($category_products as $product): ?>
<?php endforeach ?>
有了这个函数,我可以从类别ID 1中获取产品。
有没有办法使用这一个函数,并从视图传递到模型变量,我需要在foreach中获取哪个类别?
还是其他什么方式
例如:
<?php foreach ($category_products[1] as $product): ?>
<?php endforeach ?>
或
<?php foreach ($category_products[2] as $product): ?>
<?php endforeach ?>
@更新:
视图
<?php foreach ($this->product_model->get_products_by_category_id(1) as $product): ?>
控制器:
$data["category_products"] = $this->product_model->get_products_by_category_id($id);
型号:
//get products by category ID
public function get_products_by_category_id($id)
{
$lc_key = get_location_cache_key($this);
$key = "special_offers_lang_" . $this->selected_lang->id;
$result_cache = get_cached_data($this, $key, "pr");
if (!empty($result_cache)) {
if (!empty($result_cache[$lc_key])) {
return $result_cache[$lc_key];
}
} else {
$result_cache = array();
}
$this->build_query();
$this->db->where('products.category_id', $id);
$this->db->order_by('products.created_at', 'DESC')->limit(20);
$result = $this->db->get('products')->result();
$result_cache[$lc_key] = $result;
set_cache_data($this, $key, $result_cache, "pr");
return $result;
}
这工作正确,并给我正确的输出。但我也得到的问题:
Message: Undefined variable: id
Filename: controllers/Home_controller.php
当我从以下位置删除ID时:
$data["category_products"] = $this->product_model->get_products_by_category_id();
然后网站关闭:
Type: ArgumentCountError
Message: Too few arguments to function Product_model::get_products_by_category_id(), 0 passed in /home/design/domains/public_html/application/controllers/Home_controller.php on line 34 and exactly 1 expected
1条答案
按热度按时间8xiog9wr1#
我不建议将id从视图传递到模型(视图不应该直接与模型交互),但是您可以将id从控制器传递到模型以指定您想要的类别,然后将结果传递到视图。
将
get_products_by_category_id
函数更改为接受$id
参数,并在WHERE
子句中使用该$id
:model.php
然后在控制器中,将所需类别的id传递给函数:
controller.php
或
景色保持不变。