php - Codeigniter:连接多个表

标签 php mysql codeigniter

我有 3 个表格,其中包含以下列

ITEMS
-id
-name
-category_id
-brand_id

ITEM_BRAND
-id
-name

ITEM_CATEGORY
-id
-name

我加入他们

$this->db->order_by('items.name', 'ASC');
    $this->db->join('item_brand', 'item_brand.id = items.brand_id');
    $this->db->join('item_category', 'item_category.id = items.category_id');
    $query = $this->db->get("items");

问题:

既然选择了所有列,是否可以从确定的表(例如item_brand.name)中选择列?

我执行了以下代码,但得到的结果为零。 但如果我删除以下行,

$this->db->join('item_category', 'item_category.id = items.category_id');

并将$data['name']加载到 View 中,我得到的只是brand.name

我需要加入 3 个表。但我没能做到。

编辑: 我设法为这些列制定一个解决方案,但是,连接 3 个表时得到的结果为零。

$this->db->select('items.name, 
        items.category_id, 
        items.srp, 
        items.dp, 
        items.brand_id, 
        items.id, 
        items.serial, 
        item_brand.name AS item_brand, 
        item_category.name AS item_category');
    $this->db->order_by('items.name', 'ASC');        
    $this->db->join('item_category', 'item_category.id = items.category_id');
    $this->db->join('item_brand', 'item_brand.id = items.brand_id');
    $query = $this->db->get("items");

最佳答案

Is it possible to select a column from a definite table(such as item_brand.name)?

是的,您可以使用select从明确的表中选择列,如下所示:

 $this->db->select('item_brand.name');
 $this->from('items');
 $this->db->join('item_brand', 'item_brand.id = ems.brand_id');
 $this->db->join('item_category', 'item_category.id = items.category_id');
  $query = $this->db->get("items");

如果您在加入 item_category 表时未获得结果,即

$this->db->join('item_category', 'item_category.id = items.category_id');

那么外键肯定有问题,即join使用mysql的inner join,它获取连接表之间的所有相交(公共(public))数据,并且不能有匹配 item_categoryitems 表中的 id(外键)。因此,您可以使用rightjoin来获取数据。如果 items 表中存在任何匹配的外键 (items_category.id),它将获取 items 表中的所有数据以及 item_category 表中的所有数据。 所以,你可以做的是:

 $this->db->select('item_brand.name');
 $this->from('items');
 $this->db->join('item_brand', 'item_brand.id = ems.brand_id');
 $this->db->join('item_category', 'item_category.id = items.category_id','right');
  $query = $this->db->get("items");

如果您想了解更多信息,可以访问this文档。

希望有帮助。快乐编码:)。

关于php - Codeigniter:连接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35921784/

相关文章:

php - yii 图标的 imperavi 编辑器未加载

javascript - php stristr 函数在java中等效吗?

php - CodeIgniter:无法使用提供的设置连接到数据库服务器错误消息

php - MySQL 中的表布局

php - CodeIgniter form_validation 没有显示错误

php - 如何从MSSQL导出图像并将其显示在网站上?

php - 如何在 facebook graph api 请求中使用 cURL

php 不能在 html 文件中运行,但可以在外部运行

file - codeigniter 文件上传 - 可选?

php - 如何在编辑方法中停止在 codeigniter 中更新密码?