如何使用 CodeIgniter 的查询生成器方法实现逗号分隔的 JOIN 查询

问题描述 投票:0回答:2

我正在尝试使用 CodeIgniter 的活动记录从具有一些外键的表中获取数据,但我没有得到任何结果(或错误)。我下面的模型方法哪里出了问题?

public function fetch_customer()
{
    $s = 'customer.stb_id';
    $w_array = array('set_top_box.stb_id' => $s );
    $customers = $this->db
        ->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
        ->from('customer,set_top_box')
        ->where($w_array)
        ->get();
    return $customers->result();
}
php mysql codeigniter join query-builder
2个回答
1
投票

您好,您不能在 form () 子句中添加多个表名,您可以像这样使用 join()

public function fetch_customer()
    {
        $s = 'customer.stb_id';
        $w_array = array('set_top_box.stb_id' => $s );
        $customers = $this->db->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
                              ->from('customer')
                              ->join('set_top_box','here on clause ')  
                              ->where($w_array)
                              ->get();
            return $customers->result();
    } 

0
投票

本页有一些不实内容。

  • “from() 中不能有多个表”@AdrienXL

  • “不能在form()子句中添加多个表名”@Divyesh

事实上,“old skool”逗号连接表是 SQL 允许的,并且 CodeIgniter 在构建的查询中正确引用了这些表名。

可以在此处找到众多解释之一。


也就是说,使用逗号 JOIN 通常被认为已经过时且难以阅读。 相反,应使用带有 ON 子句的 JOIN(也称为 INNER JOIN),而不是通过 WHERE 表达连接表关系。

顺便说一句,因为两个表中的列名都是

stb_id
,如果您使用的是 PostgreSQL、MySQL、Oracle、SQLite 或 MariaDB,那么您可以使用 USING 作为传统 ON 条件的更简洁替代方案。 遗憾的是,CodeIgniter 没有提供方便的查询构建器方法来适应这种有效的语法。

要实现带有 WHERE 条件的逗号 JOIN 查询,以下是可行的:

public function fetch_customer(): array
{
    return $this->db
        ->select([
            'c.c_name',
            'c.acc_no',
            'c.stb_id',
            'c.mobile_no',
            'c.subscription_amount',
            'c.c_status',
            'stb.stb_no'
        ])
        ->where('c.stb_id', 'stb.stb_id', false) #<-- see 3rd parameter
        ->get('customer c, set_top_box stb')
        ->result();
}

您的编码尝试未返回任何结果的原因是因为您的数据库在

set_top_box
中不包含任何值,其中
stb_id
列等于字符串
stb.stb_id

您需要在

where()
方法调用中添加第三个参数,以通知它不要对第一个参数键/值应用任何引用。

也正是因为这个原因,

get_where()
不能用于此任务,因为它没有关闭引用的参数。


理想情况下,您应该放弃逗号 JOIN,而使用带有 ON 条件的显式 JOIN 子句。 CodeIgniter 更干净且支持更好。

public function fetch_customer(): array
{
    return $this->db
        ->select([
            'c.c_name',
            'c.acc_no',
            'c.stb_id',
            'c.mobile_no',
            'c.subscription_amount',
            'c.c_status',
            'stb.stb_no'
        ])
        ->join('set_top_box stb', 'c.stb_id = stb.stb_id')
        ->get('customer c')
        ->result();
}
© www.soinside.com 2019 - 2024. All rights reserved.