1

I started a new project with CodeIgniter and I create three tables for users and posts and likes like this

user table has these records

  1. User_ID
  2. FullName
  3. UserName

post table has these records

  1. Post_ID
  2. Title
  3. User_ID

that user_id field save creator user_id

and like table

  1. Like_ID
  2. User_ID
  3. Post_ID

I want to join this three tables and I can do it but I need join two result like this and I don't know what can I do

  $this->db->select('*');
  $this->db->from('Post');
  $this->db->join('User', 'User.User_ID = Post.User_ID', 'left');
  $query = $this->db->get();
  return $query->result();

and this

  $this->db->select('*');
  $this->db->from('Like');
  $this->db->where('User_ID' = $id);
  $query = $this->db->get();
  return $query->result();

and then join these results with together.

5
  • What do you want exactly ? can you give dummy data to explain what you want to obtain please ? You can do it with a single SQL query no ? Commented Jun 22, 2016 at 14:34
  • What data exactly you want ? and what are the fields to compare ? Commented Jun 22, 2016 at 14:35
  • I need join the first result with second result or I need select all post and I understand current user like which one post or not Commented Jun 22, 2016 at 14:47
  • @AmirNahravan can you elobarate with what you expect as answer. Example is better. Commented Jun 22, 2016 at 14:57
  • Should we presume that you want to join the post, user, and like tables and then merely count the number of related records in the like table? See also: CodeIgniter query builder to JOIN, GROUP BY, and COUNT() rows from one table and codeigniter join count another table and Codeigniter count associated records between 2 tables Commented Oct 23 at 3:59

2 Answers 2

5

You can join multiple tables in single codeigniter query

$this->db->select('*');
$this->db->from('Post');
$this->db->join('User', 'User.User_ID = Post.User_ID', 'left');
$this->db->join('Like','Like.Post_ID = Post.Post_ID AND User.User_ID = $id','left');
$query = $this->db->get();
return $query->result();
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand your question correctly, you would like to determine which posts the current user likes. The sql statement would look like sg like the following:

select p.*, u.*, l.user_id as like_user_id
from post p
inner join user u on u.user_id=p.user_id    -- I do not think you need a left join here
left join `like` l on p.post_id=l.post_id and l.user_id=$id 

I the like table is left joined to the post table using the common post_id fields. In case l.user_id is null, then the current user does not like the post. Based on the above query and your 1st codeigniter code, you should be able to create the codeigniter version of this query.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.