Welcome Guest, Not a member yet? Register   Sign In
Consolidating queries or reusing model code a good idea?
#1

[eluser]gwerner[/eluser]
I've going back through my models and it seems that they could be optimized to reduce code. Before I even start to attempt this I thought I'd see if is advisable. Or, would I spend more time on something that might not even be necessary. I searched this topic on Google, but didn't really turn up anything. Which, leads me to believe that maybe it's not necessary?

This mostly applies to SELECT statements. Update and Inserts are usually simply handled through a single method that is universal for any table as long as you supply the table, column id and data.my SELECT queries are falling into 3 categories for the most part.

1. SELECT that retrieves all or most rows with limited columns returned
2. SELECT that retrieves a single row with most columns returned
3. SELECT that is complex (joins and/or other mySQL specific language) and will require an individual method

Should I try to create methods that can handle both returning single or multiple rows? I could pass a parameter to define what type of query and limits. Not sure how to handle the actual SELECT statement if the fields needed to retrieve change?

Also, This code seems to show up quite a bit and adds a lot to the length of the model files. Especially as I keep adding SELECTS to the model.

Code:
$query = $this -> db -> get();

if($query -> num_rows() > 0)
{
foreach($query->result_array() as $row)
{
  $data[] = $row;
}
return $data;
}
else
{
return false;
}

Anyway, you understand what I'm thinking. Thanks for any tips or directions anyone might point me in.
#2

[eluser]NeoArc[/eluser]
$query->result_array() returns an array of arrays. There is no need to loop it, except when you need to modify every row before sending the values to the view.
#3

[eluser]NeoArc[/eluser]
About your question, I think is better to have these methods in a parent class that extends CI_Model:

- Select by id (asuming all your primary keys are named "id" or similar )
$car = $this->cars_model->byId(345, 'id, name, age, $rows = created_on, active');

- A query method by property=>value:
$results = $this->cars_model->byValue('name', 'Fred', $rows = 'id, name, age, created_on, active', $multiple=true);


But, I'd only use these methods to obtain a single row.
#4

[eluser]gwerner[/eluser]
[quote author="NeoArc" date="1345498085"]$query->result_array() returns an array of arrays. There is no need to loop it, except when you need to modify every row before sending the values to the view.[/quote]

Thanks for this tip. Not sure why I was doing it the other way.




Theme © iAndrew 2016 - Forum software by © MyBB