Codeigniter's Model with QueryBuilder JOIN query Codeigniter's Model with QueryBuilder JOIN query codeigniter codeigniter

Codeigniter's Model with QueryBuilder JOIN query


Query builders have their limits. That's why the query method exists. If you have a complex query I'd advise you to just use $this->query();.
It will make you lose less time and effort converting something you know already works. And in the top of that, while converting complex queries you usually end up using the query builder but with big part of your SQL in it.

In your model extending CodeIgniter\Model :

    $query = $this->db->query("SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = \$brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size");    // your array result    $result_array = $query->getResultArray();    // your object result    $result_object = $query->getResult();


BaseBuilder Class in Codeigniter expects the first join parameter to be the table name. So try passing the table name and join it on the table name itself. I haven't personally used the table aliases so I might also be wrong.

Following are the parameter that the JOIN query expects :

    public function join(string $table, string $cond, string $type = '', bool $escape = null)

Here, it expects the first name be a table, so try out by switching aliases for the table's name directly.

For your second part of query, It would be better if you could show the whole error rather than just posting the first of the error.


Managed to figure it out in the end:

    public function brand_name($brand_name_slug)    {        return $this                    ->db                    ->table('shop a')                    ->select()                    ->join('(SELECT sku, MIN(sale_price) AS sale_price FROM shop GROUP BY sku) AS b', 'a.sku = b.sku AND a.sale_price = b.sale_price')                    ->where('availability', 'in stock')                    ->where('a.sku !=', '')                    ->where('brand_name_slug', $brand_name_slug)                    ->groupBy('a.sku')                    ->orderBy('brand_name, subbrand_name, product, size, unit')                    ->get()                    ->getResult();    }

Thanks for all your pointers!