phpmysqlcodeignitercodeigniter-datamapper

Codeigniter: How to make a desc order between 3 tables?


So I am using CodeIgniter and DataMapper. I made something like a wall where you can view articles link posts image posts. This are 3 different tables and each one of them have column called 'pubdate'. At the moment when you view the wall where all of them are displayed and there are old articles but newer link posts, because they don't 'share' the same pubdate and it is ordering correctly for each table individually.

Any ideas how to make them with kind of shared pubdate so when I upload a new image post to be at the top of my Wall page ?


Solution

  • Your solution is UNION. Since you are fetching data from 3 different table that has no relations between them, so better to use UNION. Also codeigniter's active record doesn't support UNION, so you have to write the whole sql query. Check this out -

    $sql = "(SELECT colA, colB, pubdate as dt FROM articles) UNION
            (SELECT colM, colN, pubdate as dt FROM link_posts) UNION 
            (SELECT colX, colZ, pubdate as dt FROM image_posts)
            ORDER BY dt DESC
           ";
    
    $query = $this->db->query($sql);