datamapper codeigniter中的内连接

时间:2015-10-03 05:14:31

标签: php mysql codeigniter datamapper codeigniter-datamapper

我有两个表productscategories,我希望获得所有带有类别名称的产品。

产品表(产品)

id (auto_increment) | Name(varchar) | category_id(int) | price(decimal)  | user_id(int)

类别表(类别)

 id(auto_increment) | name(varchar)

必填查询: SELECT * FROM products p INNER JOIN categories c ON (p.category_id = c.id) WHERE p.user_id = 1

型号product.php

class Product extends DataMapper {

var $has_many = array('category');

var $validation = array(
    'name' => array(
        'label' => 'Name',
        'rules' => array('required', 'trim', 'alpha_dash', 'min_length' => 3),
    ),
    'category_id' => array(
        'label' => 'Category Id',
        'rules' => array('required', 'trim', 'alpha_dash'),
    ),
    'price' => array(
        'label' => 'price',
        'rules' => array('required', 'trim', 'alpha_dash'),
    ),
    'quantity' => array(
        'label' => 'quantity',
        'rules' => array('required', 'trim', 'alpha_dash'),
    ),
);

function get_product_from_userid($product_id){

    $product_obj = new Product($product_id);

    $product_obj->category->get();
}
}

模型category.php

class Category extends DataMapper {
    var $table = 'categories';
    var $has_many = array('product');
}

控制器(用户)

class Users extends CI_Controller {

function Users(){
    parent::__construct();
    $this->load->helper('url');
    $this->load->helper('form');

}
function index(){
    $product_obj = new Product();
    $product_obj->user_id = 1;
    $product_id = 1;
    $product_obj->get_product_from_userid($product_id);
}

}

1 个答案:

答案 0 :(得分:0)

Datamapper ORM for CodeIgniter does not seem to have the ability to do INNER JOIN, and defaults to LEFT OUTER JOIN.

Therefore I would use ActiveRecord for your INNER JOIN query.

$result_set = $this->db->join('categories', 'categories.id = products.category_id')->where('user_id = 1')->get('products')->result_array();

Source: I use DataMapper ORM in my job.