Codeigniter mysql join same table twice

对着背影说爱祢 提交于 2019-12-06 06:17:57

This is very simple

$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();

Have you tried forcing an alias in the join function (the "AS" operator won't work in the select clause as you have it...)?

<?php
$this->db->select('mailsystem.*, modtager.username AS modtager_name, afsender.username as afsender_name')
    ->join('`users` `modtager`', 'mailsystem.recipent = modtager.id', 'left')
    ->join('`users` `afsender`', 'mailsystem.sender = afsender.id', 'left');

$this->db->order_by('mailsystem.id', 'DESC');

return $this->db->get('mailsystem')->result();
uzsolt

Please check Codeigniter ActiveRecord: join backticking! Similar problem, maybe you will have an idea to a workaround.

you can use this :

$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();

*If you are using any db prefix use this *

$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND '.$this->db->dbprefix('mailsystem').'.sender = '.$this->db->dbprefix('afsender').'.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
Its very easy to get data from single table
$this->db->select('a.*,b.fname AS cname,c.fname as uname'); 
$this->db->from('tbl_menus a'); 
$this->db->join('tbl_admin_login b', 'b.id = a.create_by', 'left'); 
$this->db->join('tbl_admin_login c', 'c.id = a.update_by', 'left'); 
$this->db->order_by('a.id', 'desc'); 
return $this->db->get()->result_array();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!