简体   繁体   中英

MYSQL Query to Codeigniter Query

I have the query below that works fine when I use it in phpMyAdmin, I am just a bit unsure how to do it within the CI framework when I have the m.id etc in place.

Query:

SELECT DISTINCT m.name, m.id, c.id, c.name
FROM  `default_ps_products` p
INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id

There are many ways.

Example 1:

$result = $this->db
    ->select('m.name, m.id, c.id, c.name')
    ->distinct()
    ->join('default_ps_products_manufacturers m', 'p.manufacturer_id=m.id')
    ->join('default_ps_product_x_cats x', 'p.id=x.product_id')
    ->join('default_ps_products_categories c', 'x.category_id=c.id')
    ->get('default_ps_products p')
    ->result();

echo $this->db->last_query();

Sometimes the active record can't produce the query you want. So you can write it yourself.

Example 2:

$query = "SELECT DISTINCT m.name, m.id, c.id, c.name
           FROM  `default_ps_products` p
           INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
           INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
           INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id";

$result = $this->db
    ->query($query)
    ->result();

echo $this->db->last_query();

In this second example, db::query() can take an array as the second parameter that will replace any question marks (?) within $query with the respective value. For example say you needed to add some where values to your query.

Example 3:

$query = "SELECT DISTINCT m.name, m.id, c.id, c.name
          FROM  `default_ps_products` p
          INNER JOIN  `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
          INNER JOIN  `default_ps_product_x_cats` x ON p.id = x.product_id
          INNER JOIN  `default_ps_products_categories` c ON x.category_id = c.id
          WHERE c.id=?";

$result = $this->db
    ->query($query, array(1))
    ->result();

echo $this->db->last_query();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM