StephanB
StephanB

Reputation: 39

CodeIgniter, how to return multiple queries from model to controller?

I'm trying to get my model to return two queries, one for the data itself which are multiple records from the table 'Categories', and a count field, from the table 'Posts'.

I've tried alot of possible solutions, but so far none fixed it for me.

My view does work with the correct route /forum/$id, but loading the categories and a post count per category won't work.

Categories Controller:

$this->load->database();
$this->load->model("Categories_model");

$results=$this->Categories_model->getCategories();

$data=array('results'=>$results);

$this->load->view('Categories_view',$results);

Categories Model:

// this works if I only want to get all the categories  
// $query=$this->db->get('Categories');
// return $query->result();

$query1 = $this->db->get('Categories');
$query2 = $this->db->query("SELECT COUNT(*) AS rowCount FROM Posts");

$return array('categories' => $query1, 'count' => $query2);

Categories View:

<tbody>
    <?php foreach ($results['categories'] as $r):?>
        <tr>
            <td><a href="<?php echo site_url('forum'); ?>/<?=$r->CategorieId?>"><?=$r->Name?></a></td>
            <td><?=$r->rowCount?></td>
        </tr>
    <?php endforeach;?> 
</tbody>

When I load the Categories view, I get this error:

syntax error, unexpected 'array' (T_ARRAY), Filename: models/Categories_model.php

Can somebody help me with some sample code on how to do this, or a fix for my current code?

Thank you in advance!

Upvotes: 2

Views: 12901

Answers (3)

Rain
Rain

Reputation: 601

Running Transactions:
To run your queries using transactions you will use the $this->db->trans_start() and $this->db->trans_complete() functions as follows:

$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure of any given query. Click here to see more

Upvotes: 1

Arcanyx
Arcanyx

Reputation: 870

$query['categories'] = $this->db->get('Categories')->result_array();
$query['count']  = $this->db->query("SELECT COUNT(*) AS rowCount FROM Posts")->result();

return $query;

Try this. Not done anything great. Just used result_array() and result(). I hope they are compatible with your version of CI!!

Upvotes: 0

Saty
Saty

Reputation: 22532

return is wrong in your code remove $ from your return type

$return array('categories' => $query1, 'count' => $query2);

it should be

return array('categories' => $query1, 'count' => $query2);

Upvotes: 3

Related Questions