简体   繁体   中英

How to convert mysql query to codeigniter using query builder?

The following is my mysql query:

select * from db_posts LEFT JOIN db_followers  ON db_posts_user_id = db_followers_following AND db_followers_user_id = 276

How can I convert it to codeigniter using query builder?

$this->db->where('db_posts_user_id', 'db_followers_following');
$this->db->where('db_followers_user_id', 276);
$this->db->order_by('db_posts.db_posts_id', 'DESC');
$this->db->join('db_followers', 'db_followers.db_followers_following = db_posts.db_posts_user_id');
$query2 = $this->db->get('db_posts')->result_array();

I get the required result when I use mysql query. But I get a blank array when I use codeigniter queries. What is wrong in my CI Query?

Try adding the "Left" option to tell it what kind of join to do:

$this->db->join('db_followers', 'db_followers.db_followers_following = db_posts.db_posts_user_id', 'Left');

Also I'm not sure you need

$this->db->where('db_posts_user_id', 'db_followers_following');
  • this is already covered by your JOIN statement.

Source: http://www.bsourcecode.com/codeigniter/codeigniter-join-query/#left-join and https://www.codeigniter.com/userguide3/database/query_builder.html

why are you using those where clause? if you are using it as condition for your 'JOIN' process, try it like this:

$this->db->order_by('db_posts.db_posts_id', 'DESC');
$this->db->join('db_followers', 'db_followers.db_followers_following = db_posts.db_posts_user_id and db_followers_user_id = 276', 'left');
$query2 = $this->db->get('db_posts')->result_array();

Points to Note

1)as previous comments said, you should 'Left Join' if you want to get all posts from 'db_posts'.

2) You can add Multiple conditions in ON Clause using and but within ''. all your conditions should be specified before second comma(,) which is before mentioning 'LEFT'.

Hope this will help. Lemme know if this help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM