codeigniter - list related data

Asked

Viewed 792 times

0

Hello,

I’m trying to show the name of a channel associated with an event through a FK, but I can’t show it.

Model:

public function get_events() {
$this->db->get('events');
$this->db->join('channels', 'events.channel_id = channels.id');
$this->db->join('colors', 'channels.color_id = colors.id');
return $query = $this->db->get('events')->result();}

View:

foreach($events as $event){  
echo '<tr class="odd gradeX">';
    echo "<td>".$event->start." - ".$event->end."</td>";
    echo '<td class="center">'.$event->channels->name.'</td>';
    echo '<td class="center">'.$event->status_id.'</td>';
echo "</tr>";}

Any suggestions?

  • Does not display the records or they come wrong?

  • 1

    This Return $query. Place: Return $this->db->get('Events')->result();

  • I can see everything from the first entity, Events, but if I want to show from the second entity, Channels I can’t.

2 answers

0

Do it like this:

Model

public function get_events() {
 $this->db->select('*');
 $this->db->from('events');
 $this->db->join('channels', 'events.channel_id = channels.id');
 $this->db->join('colors', 'channels.color_id = colors.id');
 return $this->db->get()->result();
 }

Controller

public function pagina() {
    $this->load->model('evento_model', 'evento');
    $dados['events'] = $this->evento->get_events();
    $this->load->view("suapaginadeview.php", $dados);
}

View

foreach($events as $event){  
 echo '<tr class="odd gradeX">';
 echo "<td>".$event->start." - ".$event->end."</td>";
 echo '<td class="center">'.$event->channelname.'</td>';
 echo '<td class="center">'.$event->status_id.'</td>';
 echo "</tr>";
 }

Thus, you have access to all the data of the tables of the query(If you have any table field with the same name you will have to use nicknames in the query).

0

Good afternoon. I would change to the following code:

public function get_events() {
$this->db->Select('events.*, channels.*, colors.*');
$this->db->join('channels', 'events.channel_id = channels.id');
$this->db->join('colors', 'channels.color_id = colors.id');
$this->db->from('events');
$res = $this->db->get()->result();
return $res; 
}

That way, you have access to data from all tables. Another advice I give you, is how you do not specify differences between the ids, work with the apelidos as: event.id as idevents or channels.id as idchannels

I hope I’ve helped.

Oss

Browser other questions tagged

You are not signed in. Login or sign up in order to post.