【问题标题】:bonfire codeigniter chaining model methods篝火codeigniter链接模型方法
【发布时间】:2023-03-26 23:36:02
【问题描述】:

我只是篝火 / ci 的新手。我正在尝试通过链接 bf/ci 模型方法来重新创建以下 sql 语句:

        SELECT  prod_cat.cat_id, 
                prod_cat.prod_id, 
                prod.enabled, 
                prod.name,
                prod.prod_id,   
        FROM prod_cat, prod 
        WHERE prod.is_enabled = 1 
        AND prod_cat.cat_id =15 
        AND prod_cat.prod_id = prod.prod_id 
        ORDER BY prod.name DESC

我有一个 bf / ci prod_model 和一个 prod_cat_model。

我知道我可以执行以下操作来获取所有匹配 cat_id 15 的 prod,例如:

 $this->load->model('cat/prod_cat_model');  
 $records = $this->prod_cat_model->find_all_by('cat_id' => $cid);

同样,我计划使用产品表上的 find_all_by 来限制活动/启用的记录,如下所示:

 $this->prod_model->find_all_by('enabled', 1);

首先,作为测试,我正在考虑尝试通过将数组传递给 prod_model 来组合这两个代码,如下所示:

  public function productsincategory($cid)
  {
    $this->load->model('cat/prod_cat_model');   
    $criteria = array(
    'enabled' => 1,
    'prod_id' => $this->prod_cat_model->find_all_by('cat_id', $cid)
    );
    $records = $this->prod_model->find_all_by($criteria) ;
  }

我收到一条错误消息:

“where 子句”中的未知列“数组”

SELECT * FROM (prod) WHERE enabled = 1 AND prod_id = 数组

这是有道理的......但我不知道如何修复它,以便它类似于“select * from prod where enabled = 1 and prod_id in (prod ids from prod_cat table) 我也尝试过使用“where_in()”,但篝火似乎无法识别。 谢谢。

【问题讨论】:

  • 你试过使用 php-activerecord sparks 吗?您不需要对每个模型进行查询。对于产品和类别,您只需要 Category::find(1)->include('products')。当然,您必须在模型上设置关系。

标签: php codeigniter


【解决方案1】:

我在我的产品模型中创建了自己的 where_in() 方法,如下所示:

public function where_in($field=NULL, $value=NULL)
{
    if (!empty($field))
    {
        if (is_string($field))
        {
            $this->db->where_in($field, $value);
        }
        else if (is_array($field))
        {
            $this->db->where($field);
        }
    }

    return $this;

}//end where()

所以在我的控制器中,我做了这样的事情:

  public function productsincategory($cid)
  {
    $this->load->model('cat/prod_cat_model');  
    $this->prod_cat_model->where('cat_id', $cid);
    $records = $this->prod_cat_model->find_all();

 $prod_ids = array();

foreach($records as $record)
{
    array_push($prod_ids, $record->product_id);
}

    $this->prod_model->where_in('prod_id', $prod_ids) ; //call our own where_in method
$records = $this->prod_model->find_all();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多