CodeIgniter:如何连接两个表列并使用类似活动记录来查询两个表?

时间:2013-04-05 04:15:38

标签: codeigniter search activerecord

public function search($query, $limit) {
    // output
    $output = "";
    // query
    $this->db->select("*");
    $this->db->from("products");
    $this->db->like("brand", $query);
    $this->db->or_like("model", $query);
    $this->db->limit($limit);
    $query = $this->db->get();
    // zero
    if ($query->num_rows() == 0) {
        $output .= "No results found";
        return $output;
    }
    // result
    foreach ($query->result_array() as $row) {
        // uri
        $uri2 = "{$this->base_url}specifications/{$row['brand']}-{$row['model']}";
        $uri2 = str_replace(" ", "-", $uri2);
        // price format
        $row['price'] = number_format($row['price']);
        // image url
        $image = "{$this->base_url}assets/images/products/{$row['category']}-{$row['brand']}-{$row['model']}/thumb.png";
        $image = str_replace(" ", "-", $image);
        $output .= "<ul class=\"product\">\n
            <a href=\"{$uri2}\">\n
                <li class=\"product-image\"><img src=\"{$image}\" height=\"108\" width=\"57\" alt=\"\"></li>\n
                <li class=\"product-brand\">{$row['brand']}</li>\n
                <li class=\"product-model\">{$row['model']}</li>\n
                <li class=\"product-price\">{$row['price']} <span class=\"green\">pkr</span></li>\n
            </a>\n
        </ul>\n";
    }
    // return
    return $output;
}

我在这里做了三种类型的查询:

1-仅包含品牌的查询(我得到结果)
2-只包含模型的查询(我得到结果)
3-查询包含两者(我没有得到结果)

如何完成以上三项任务?

2 个答案:

答案 0 :(得分:0)

您似乎正在执行某种搜索,因此您希望得到的结果来自控制器或视图,如果像这样的条件,则执行该操作,然后执行此操作

if ($brand_val != '' )
{  //put your where query here }

if ($model_val  != '' )
{  //put your where query here }

if ($brand_val != '' && $model_val  != ''   )
{  //put your where query here }

希望这会给出想法

答案 1 :(得分:0)

用它来打印查询。

echo $ this-&gt; db-&gt; last_query();

然后尝试在phpmyadmin中执行该查询