Setup:
Codeigniter 3 running on a variant of PHP 5 server. Using the Query Builder to deal with the db.
Background:
Creating a software that has a client profile. Users can add multiple notes to the profile, and link a contact to that note. The profile then displays all the notes and the contact on the corresponding profile, using the join()
method from Codeigniter 3's Query Builder.
Issue:
A note can be added without a client contact, in the case of a generalised note. This sets the default value of NULL
in the DB which in turn prevents the client_model from returning the notes, because it cant join the tables.
Current code:
function get_client_notes($client_id)
{
$this->db->join('nh_note_types', 'nh_note_types.type_id = nh_client_notes.client_notes_type');
$this->db->join('nh_user_profiles', 'nh_user_profiles.user_profile_user_id = nh_client_notes.client_notes_added_by');
$this->db->join('nh_client_contacts', 'nh_client_contacts.client_contact_id = nh_client_notes.client_notes_client_contact_id');
$this->db->order_by("client_notes_added_date", "desc");
$query = $this->db->get_where('nh_client_notes', array('client_notes_client_id' => $client_id));
return $query;
}
Currently if the value for client_notes_client_contact_id
is NULL
it will not return any data for that row.
What I am trying to find out is if there is a way to do the following: IF the client_notes_client_contact_id
is not null then join the tables, else carry on past.
Or any other way that would join the tables if there is a value and where it is NULL
, then don't join.
Any help is appreciated!
Your current MySQL query with the above Query builder would 'build' like this:
SELECT
*
FROM
nh_client_notes
JOIN nh_note_types ON
( nh_note_types.type_id = nh_client_notes.client_notes_type )
JOIN nh_user_profiles ON
( nh_user_profiles.user_profile_user_id = nh_client_notes.client_notes_added_by )
JOIN nh_client_contacts ON
( nh_client_contacts.client_contact_id
=
nh_client_notes.client_notes_client_contact_id
)
WHERE
client_notes_client_id = 479
ORDER BY
client_notes_added_date DESC
However, this will require all the JOINs to have an matching ID Available. Thus the correct MySQL would be LEFT JOIN
on client_notes_client_contact_id
key, which is as you've requested to be conditional .
In this instance, adjust your Query builder to have a third parameter on the join()
to make this 'left'.
<?php
$this->db->join(
'nh_client_contacts',
'nh_client_contacts.client_contact_id = nh_client_notes.client_notes_client_contact_id',
'left'
);
?>
In doing so, this'll correct your query to bring back client_notes regardless of client_notes_client_contact_id
.
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.