Reputation: 156
I'am trying to join two tables. Lets say t1
and t2
. t1
has fk t2_id
. but when I run the code nothing is shown in my view.
Controller:
//..
$data['city']= $this->state_model->name();
$this->load->view('viewt', $data);
Model:
function name(){
$this->db->select('*');
$this->db->from('state');
$this->db->join('city', 'city.state_id = state.id');
$sql = $this->db->get();
if ($sql->num_rows () >0) {
foreach($sql->result() as $row) {
$this->db->where('state_id','state.id');
$r = $this->db->get('city');
}
return $r->result();
}
else {
return null;
}
View:
<?php foreach($city as $row):?>
<?php echo $row->cityname; ?></br></br></br>
<?php endforeach;?></br></br>
Thanks in advance
The Queries:
SELECT `id`, `statename` FROM (`state`) ORDER BY `id` ASC SELECT * FROM (`state`) JOIN `city` ON `city`.`state_id` = `state`.`id` SELECT * FROM (`city`) WHERE `state_id` = 'state.id' SELECT * FROM (`city`) WHERE `state_id` = 'state.id' SELECT * FROM (`city`) WHERE `state_id` = 'state.id'
Upvotes: 0
Views: 2591
Reputation: 13630
OK, so you're getting three records back from your join - so we know that's working. But you're other 3 queries look incorrect. Try this:
if ($sql->num_rows () >0) {
$r = array();
foreach($sql->result() as $row) {
// here, you need to replace 'state.id' with the actual
// results from your join query ($row->id which is the id
// from the state table
$this->db->where('state_id',$row->id);
$r[] = $this->db->get('city')->result();
}
return $r;
}
else
{
return null;
}
So now you should have an array of results and can iterate with the foreach in your view.
Upvotes: 0
Reputation: 3253
I don't quite understand why you need a second query inside a loop. Can't you just do:
if ($sql->num_rows() > 0) {
return $sql->result();
}
?
Upvotes: 0
Reputation: 37701
Your $r variable will only have the last iteration thus the function will only return the last result set, so try this:
if ($sql->num_rows () >0) {
foreach($sql->result() as $row) {
$this->db->where('state_id',$row->state_id);
$r[] = $this->db->get('city')->row();
}
return $r;
Upvotes: 1