Reputation: 10077
I'm thinking about efficiency, and I'm not really sure about it one way or another.
But I have a bunch of rows with multiple columns. I just need the name field from all the rows where a certain other key is a certain value. I can get all these rows like this:
$this->db->where('res_id', $res_id);
$q = $this->db->get('products');
return $q->result();
then i can foreach through the array that it returns and only use name method of each object liek this:
foreach($returned_value as $fun):
echo $fun->name;
endforeach;
But I'm wondering, would it be more efficient to only select the name attribute from each row, and I feel stupid asking it cause I've been using active record forever, but how would I go about this. I realize I could write it out using the $this->db->query()
function, but is there a way to specify it using the main active record commands?
Upvotes: 6
Views: 47811
Reputation: 47972
Neither CI3 nor CI4 offer an active record method to isolate a column of data from a query's result set. The sleekest you can program it would be to callarray_column()
on the 2d result set.
public function getProductNamesById(int $res_id): array
{
return array_column(
$this->db->select('name')
->get_where('products', ['res_id', $res_id])
->result(),
'name'
);
}
Upvotes: 0
Reputation: 2180
$this->db->select('name');
$this->db->from('tblNAME');
$this->db->where('res_id', $res_id);
return $this->db->get()->result();
It is quicker and more efficient I suppose as you are not returning everything.
UNTESTED
Here is a tested function I use which you might find good reeference
function get($id = null)
{
$this->db->select('id, Username, First_Name, Last_Name, Role, Email');
$this->db->from('user');
if (!is_null($id)) $this->db->where('id', $id);
$this->db->order_by('id', 'desc');
return $this->db->get()->result();
}
Upvotes: 10