有很多方法。
示例 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();
有时活动记录不能产生您想要的查询。所以你可以自己写。
示例 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();
在第二个示例中,db::query() 可以将数组作为第二个参数,它将 $query 中的任何问号 (?) 替换为相应的值。例如,假设您需要在查询中添加一些 where 值。
示例 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();