I have two tables
Table one is a list of documents
documents:
+-------------+---------------+
| document_ID | document_name |
+-------------+---------------+
| 1 | test.pdf |
+-------------+---------------+
| 2 | other.pdf |
+-------------+---------------+
Table two is a list of users who have used that document. It is a 1-1 relationship – i.e. a user will only ever use a document ONCE (or not at all).
documents_users:
+-------------+---------------+-----------+---------------+
| document_ID | user_ID | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | 5 | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 1 | 7 | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | 5 | 1 | stuff |
+-------------+---------------+-----------+---------------+
When a user is browsing the list – I need to be able to show ALL documents, plus IF they have access it or not
So for example the desired output for user 5 in the example above is;
+-------------+---------------+-----------+---------------+
| document_ID | document_name | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | test.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | other.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
while the desired output for user 7 is
+-------------+---------------+-----------+---------------+
| document_ID | document_name | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | test.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | other.pdf | | |
+-------------+---------------+-----------+---------------+
I tried doing a join along the lines of
$this->db->join('documents_users', 'documents_users.document_ID = documents.document_ID');
$this->db->where('documents_users.user_ID', '7');
return $this->get_all();
But this only returns the records that they has_read=1
I can see the problem is the “where” command – but I’m not sure what to do?
You need a (left) outer join, with the filter criterion on
user_IDmoved into the join condition rather than being in aWHEREclause: