【问题标题】:How to select data from 2 differenet tables using Codeigniter? [duplicate]如何使用 Codeigniter 从 2 个不同的表中选择数据? [复制]
【发布时间】:2021-08-26 08:55:01
【问题描述】:

我想从 2 个不同的表中选择 id 并使用两个表中都存在的 id。

卖家

id | name | mobile_number | password | is_active    
1  | abc  | 987654321     | 12345678 |  0
2  | pqr  | 989898989     | 12345678 |  1
3  | lmn  | 919191991     | 12345678 |  1

其中,0 不活跃,1 活跃。

油轮

id | seller_id | capacity    
1  | 1         | 14
2  | 2         | 7
3  | 2         | 3.5
4  | 3         | 3.5

其中,seller_id 是外键。

现在,我想选择所有状态为活动的卖家,即 is_active = 1 并且容量 = 3.5

这是我的代码。


        $data = $this->db->select('id')
                 ->from('seller')
                 ->where('is_active', 1)
                 ->get()
                 ->result();

        return $data;

    }```

```public function check_capacity($id,$capacity){

        $data=$this->db->select('seller_id',$idd)
                 ->from('tanker')
                 ->where('capacity', $capacity)
                 ->get()
                 ->result();

        return $data;
    }```

Expected Output : 

*Array
(
[0] => stdClass Object
(
[id] => 2
)

[1] => stdClass Object
(
[id] => 3
)

)*

【问题讨论】:

标签: php mysql codeigniter join codeigniter-query-builder


【解决方案1】:

您必须将这两个表连接在一起:

$this->db->select('*, seller.id as seller_id, tanker.id as tanker_id')
    ->from('seller')
    ->join('tanker', 'seller.id = tanker.seller_id')
    ->where('is_active', 1)
    ->where('capacity', 3.5)
    ->get()
    ->result();

一旦你有了这个,你可以玩弄参数(例如选择一个动态容量)。如果您遇到问题,请注意您始终可以使用以下命令打印最后一个查询:

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

【讨论】:

  • 为什么要选择所有内容 (*) 然后再选择另外两列(再次)?
  • @mickmackusa 我选择选择所有内容,以便提出问题的 preson 可以看到正在发生的事情。由于 CI 只会返回第二个 id 列(并且会覆盖第一个),因此这些也会被选中。但是既然你问了这个问题,这些字段就需要一个别名。
  • 我认为您可以安全地使用select("seller.*"),因为 OP 在连接表中没有显示任何有价值的信息——油轮表仅用于过滤目的。
  • 谢谢你的回答,你能用简单的话解释一下你在那里做了什么吗?
  • 联接根据条件将两个或多个表的所有行放在一起。在这种情况下,列seller_id1 表示该行属于卖方表的id1。如果省略 where 子句并打印查询结果,您将看到油轮表的所有四行都与卖方表行匹配。您可以使用此构造,就好像表格一开始没有分开一样。你可以找到一个可视化的表示here
猜你喜欢
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多