Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'DISTINCT' in Codeigniter Active Records?

I have a query using active records.

$this->db->select('reg.users_id,reg.registration_id,reg.device_type');
$this->db->join('users as usr','usr.users_id = reg.users_id','left');
$this->db->where('usr.users_status',1);
$this->db->where('reg.users_id',91);
$query = $this->db->get('users_gcm_registration as reg');

I want to fetch DISTINCT(registration_id).

How can I do that?

like image 354
Saswat Avatar asked Jun 15 '16 12:06

Saswat


2 Answers

   $query = $this->db->select('registration_id')
                ->distinct('registration_id')
                ->from('reg')
                ->get(); 
 return $query->result();
like image 74
Avigit.M Avatar answered Sep 22 '22 08:09

Avigit.M


You can use distinct as

$this->db->distinct('reg.registration_id');
$this->db->select('reg.users_id,reg.device_type');
....

But better use group_by

$this->db->select('reg.users_id,reg.registration_id,reg.device_type');
$this->db->join('users as usr','usr.users_id = reg.users_id','left');
$this->db->where('usr.users_status',1);
$this->db->where('reg.users_id',91);
$this->db->group_by('reg.registration_id');// add group_by
$query = $this->db->get('users_gcm_registration as reg');
like image 24
Saty Avatar answered Sep 24 '22 08:09

Saty